Executing a "for" loop, but getting "array indices must be positive integers or logical values" error
1 view (last 30 days)
Show older comments
Hi,
I am trying to carry out a calculation for array "y" for each value in the array, starting from the second value. I get the "array indices must be positive integers or logical values" error, and not sure why. I think it may be getting hung up on dividing the previous "y" element in to the current "y" element. I am currently specifying "y(i - 1)" when really I want it to be "y(i) / y(previous element to the current i'th value)"
Code is as follows:
clear
clc
y = [2.903E-04, 7.538E-05, 2.525E-05, 2.136E-03, 2.051E-02];
x = [0, 6.25, 12.5, 18.75, 25];
for i = y(2):y(end)
dBa(i) = 10*log10(y(i)/(y(i-1)))
end
Thanks.
0 Comments
Answers (1)
Steven Lord
on 22 May 2020
What values does your loop variable take on when you use the code as you've written it?
y = [2.903E-04, 7.538E-05, 2.525E-05, 2.136E-03, 2.051E-02];
for k = y(2):y(end)
disp(k)
end
There's no such thing as element 7.538e-5 of an array in MATLAB. You could loop from 2 to numel(y) but that would leave dBa(1) as 0. [I'm not sure whether that's intended or not based on your code.]
for k = 2:numel(y)
fprintf('y(%d) is %g.\n', k, y(k))
end
Or you could vectorize the computation of dBa using element-wise division (./) instead of matrix division (/). For scalar values, ./ and / behave the same. For non-scalars they don't.
k = 2:numel(y);
dBa(k) = 10*log10(y(k)./(y(k-1)))
5./10
5/10
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!