MATLAB Answers

Executing a "for" loop, but getting "array indices must be positive integers or logical values" error

1 view (last 30 days)
Will Crowson
Will Crowson on 22 May 2020
Commented: Will Crowson on 26 May 2020
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

Sign in to comment.

Answers (1)

Steven Lord
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

  1 Comment

Will Crowson
Will Crowson on 26 May 2020
Thanks for the feedback.
Why would MATLAB not recognise the element 7.538E-05?
The element-wise division gives the same error also. N.B. I were to carry out this "loop" in Excel, I would carry out the following in the neighbouring cell (for example):
10*LOG(B12/B11)
10*LOG(B13/B12)
10*LOG(B14/B13)
10*LOG(B15/B14)
etc..
Hopefully that clears up what I am trying to achieve with the loop - the number of times the loop goes round may vary depending on length of the column vector.
Code is currently as follows, but I gather the error is down to the "y" values?:
clear
clc
y = [2.903E-04, 7.538E-05, 2.525E-05, 2.136E-03, 2.051E-02];
for k = y(2):numel(y)
dBa(k) = 10*log10(y(k)./(y(k-1)))
end
Thanks in advance.

Sign in to comment.

Tags

Products


Release

R2019b