Index in position 2 is invalid. Array indices must be positive integers or logical values.
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
Torsten
2022-4-7
round(N*IX) and round(N*IY) can also produce 0 as a result, and MATLAB arrays start with index 1.
采纳的回答
Voss
2022-4-7
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!