# I know that my equations are correct, but the error is telling me i need to use logical or positive values

1 view (last 30 days)
Anna Zito on 30 Jun 2020
Commented: John D'Errico on 30 Jun 2020
Hello, My current code is given below along with my error message. I know that my equations are correct so i do not know how to get the error message to go away
ERROR:
Array indices must be positive integers or logical values.
Error in Project5 (line 6)
Z1(t)=0.01*(1+0.012732*cos(3225*t)*(0.0274))-0.01;
>>
CODE:
% Let U(x,t)-U(x,0) = ZN
t=0:.01:1000;
Z1(t)=0.01*(1+0.012732*cos(3225*t)*(0.0274))-0.01;
Z2(t)=Z1(t);
Z3(t)=0.01*(1+Z1(t)+0.041888*cos(9674*t)*(0.08215))-0.01;
Z4(t)=Z3(t);
figure 1
plot(t,Z1(t))
xlabel('time')
ylabel('U(x,t)-U(x,0)')
Title ('N=1')
figure 2
plot(t,Z2(t))
xlabel('time')
ylabel('U(x,t)-U(x,0)')
Title ('N=2')
figure 3
plot(t,Z3(t))
xlabel('time')
ylabel('U(x,t)-U(x,0)')
Title ('N=3')
figure 4
plot(t,Z4(T));
xlabel('time')
ylabel('U(x,t)-U(x,0)')
Title ('N=4')

Alan Stevens on 30 Jun 2020
You are trying to index Z1 with 0.01. i.e you are telling MATLAB to to create Z1(0.01). However, the argument to Z1 (and the others) must be an integer.
Try something like
i = 1:10000
t = i/10
Z1(i) = ... etc.
Anna Zito on 30 Jun 2020
Oh wow i did not know that. Thank you so much for your help!!
John D'Errico on 30 Jun 2020
But as I think about it, now let me explain the exception. :) Consider this example:
A = rand(1,5)
A =
0.54815 0.63487 0.83716 0.34582 0.65921
>> A > .6
ans =
1×5 logical array
0 1 1 0 1
>> A(A > .6)
ans =
0.63487 0.83716 0.65921
So, the test A > 0.6 produced a vector of zeros and ones. One might wonder, based on my previous statement, that since 0 is not a valid index, so why is it that A(A > 0.6) works. That happens because the test
A > 0.6
produces a logcal vector. Note that the error message told you that you need to "use logical or positive values". Now Instead, let me try this:
A([0 1 1 0 1])
Array indices must be positive integers or logical values.
That fails, even though it looks the same. It fails, because the index vector was not a LOGICAL vector. It was created as a vector of doubles. And that leads me to one final example:
A(logical([0 1 1 0 1]))
ans =
0.63487 0.83716 0.65921
And that case worked! So if I want, I can create that vector of local 0s and 1s and now it will work, as long as they were logicals.
With that, I've explained more than you probably want to know, but one day, I hope it will prove useful.

Gurpreet Singh on 30 Jun 2020
Hi Anna
This error occurs when you attempt to index into an array using indices that are not positive integers or logical values.
Here you are using double value array "t" for indexing array Z1, Z2, Z3, and Z4. However, any matrix or array argument should always be a positive integer or logical value.
Please refer to the https://in.mathworks.com/help/matlab/learn_matlab/array-indexing.html (array-indexing) documentation for more information on how to do indexing in arrays.