Index in position 2 is invalid. Array indices must be positive integers or logical values.
1 回表示 (過去 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!