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)
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
Array indices must be positive integers or logical values.
Error in Project5 (line 6)
% Let U(x,t)-U(x,0) = ZN
figure 1
Title ('N=1')
figure 2
Title ('N=2')
figure 3
Title ('N=3')
figure 4
Title ('N=4')

Accepted Answer

Alan Stevens
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.
John D'Errico
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.

Sign in to comment.

More Answers (1)

Gurpreet Singh
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.


Find more on Resizing and Reshaping Matrices 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!