Index in position 2 is invalid. Array indices must be positive integers or logical values.
2 views (last 30 days)
Show older comments
I am getting this error "Index in position 2 is invalid. Array indices must be positive integers or logical values." but am not sure how to fix it. The error is in line 13) B(iy,ix)=A(IX(iy,ix),IY(iy,ix));
N = 1000;
A = zeros(N);
IX = rand(N);
IX = round(N*IX);
IY = rand(N);
IY = round(N*IY);
% part a
tic
for ix=1:N
for iy=1:N
B(iy,ix)=A(IX(iy,ix),IY(iy,ix));
end
end
toc
1 Comment
Torsten
on 7 Apr 2022
round(N*IX) and round(N*IY) can also produce 0 as a result, and MATLAB arrays start with index 1.
Accepted Answer
Voss
on 7 Apr 2022
This error happens because some element of IY is zero (could've just as easily been IX). That happens because round(N*IY) returns zero for some elements, i.e., some random numbers returned by rand are less than 1/(2*N) so round(N*rand) goes to 0.
You can make rand work for getting (valid) random indices, but it is probably easier to use randi (random integers):
N = 1000;
A = zeros(N);
IX = randi(N,[N N]) % an N-by-N matrix of random integers between 1 and N, inclusive
IY = randi(N,N) % different syntax for the same thing
% part a
tic
for ix=1:N
for iy=1:N
B(iy,ix)=A(IX(iy,ix),IY(iy,ix));
end
end
toc
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!