Array indices must be positive integers or logical values.

1 view (last 30 days)
I am so confused why would I get this error. One minute the code is running fine and produces plots, the next is no longer running. What is the problem with the function Rho? I cleared my workspace multiple times in case something was stuck there but still I am getting the same error. The code was working fine before.
Error message:
Array indices must be positive integers or logical values.
Error in Rho (line 35)
rho(1) = rho(1)+ q*(x_p(i) - x(end-1))/(dx^2); % rhoj
Error in WeakBeam (line 157)
[rho] = Rho(rhoe, xe, x, dx, qe);
I will be posting the code as well for you to run.

Answers (1)

Steven Lord
Steven Lord on 1 Mar 2021
If x only has one element, x(end-1) is an attempt to access element 0 of x. Arrays in MATLAB don't have an element 0. Their first element is element 1.
You may also receive this error if x is empty, has zero elements. In that case x(end-1) attempts to access element -1 of x. Arrays in MATLAB also don't have an element -1.
  1 Comment
Jamie Al
Jamie Al on 1 Mar 2021
x is an array of 0:1:101 elements so I don't see why would this be a problem cause here x(end-1) would be 99?

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!