Array indices must be positive integers or logical values.

2 views (last 30 days)
gcoord
0 0
0 0
0 0
0 0
.........
Array indices must be positive integers or logical values.
this error is coming please help

Answers (1)

Steven Lord
Steven Lord on 8 May 2023
Usually this happens when you try to use 0 as an index. Indices in MATLAB start at 1 not 0.
x = 1:10;
This will work:
y(1:2:20) = x.^2
y = 1×19
1 0 4 0 9 0 16 0 25 0 36 0 49 0 64 0 81 0 100
This won't. I've wrapped it in try and catch so code later in this answer can run.
try
z(0:2:19) = x.^2
catch ME
fprintf("This code threw error: %s\n", ME.message)
end
This code threw error: Array indices must be positive integers or logical values.
To fix this error, use indices that start at 1 not 0.
Alternately you could be trying to call a function but there's a variable by that name instead. In this case rename the variable so it doesn't have the same name as the function.
q = sin(pi)
q = 1.2246e-16
sin = 42;
w = sin(pi)
Array indices must be positive integers or logical values.

'sin' appears to be both a function and a variable. If this is unintentional, use 'clear sin' to remove the variable 'sin' from the workspace.
If you need further help you will need to show us a small sample of code with which you can reproduce this error.

Community Treasure Hunt

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

Start Hunting!