why do I get Array indices must be positive integers or logical values?

7 views (last 30 days)
Ahmed Alhawaj
Ahmed Alhawaj on 27 Jan 2020
Edited: Star Strider on 27 Jan 2020
After i run the code provided up , it shows to me in line 17 the Array indices must be positive integers or logical values
What does that mean ?
How do i fix the problem?
  1 Comment
Rik on 27 Jan 2020
Please remove the line numbers and format your code properly.
The error indicates you are trying to use a value as an array index. sin(x) is a function call if sin is a function, but sin(x) is an indexing operation if sin was assigned a value.
You should check if somewhere in your previous code you assigned a value to sin, which made it a variable. (cos seems fine, as line 13 doesn't seem to cause a similar error)

Sign in to comment.

Answers (2)

Adam on 27 Jan 2020
Edited: Adam on 27 Jan 2020
It means pretty much exactly what it says. In Matlab x1, as you create it, is an array of values representing your function at defined points. Those values are indexed as 1, 2, 3, 4, 5,..., not as the true t values of your equation. However, you can use vectorisation to assign all values at once:
x1 = uo*(1-c1.*(cos(wd1*t)-(y1*sin(wd1*t))));
Just like you do with c1, which also works with a full vector of t values.
Notice you are already using .* for your multiplication, which is what is needed for vectorised maths here since c1 and the quantity it is being multiplied by are both vectors, so this gives you element-wise multiplication and will assign all the results into x1, which will be the same length as t at the end, and that provides your link between t and x, by indexing into each.

Star Strider
Star Strider on 27 Jan 2020
Edited: Star Strider on 27 Jan 2020
The way you have defined ‘t’, it is not an integer, and the code interprets it as a subscript in lines 17-19.
One way to fix it would be to create ‘x’ as a function, then assign the ‘x’ values appropriately with calls to it:
xfcn = @(wd,cc,yy,uu,t) uu*(1-cc.*(cos(wd*t)-(yy*sin(wd*t))));
x1 = xfcn(wd1,c1,y1,uo,t);
x2 = xfcn(wd2,c2,y2,uo,t);
x3 = xfcn(wd3,c3,y3,uo,t);
I believe that covers all the options.
EDIT — Corrected typographical errors.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!