Index in position 2 is invalid. Array indices must be positive integers or logical values.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Torsten
le 7 Avr 2022
round(N*IX) and round(N*IY) can also produce 0 as a result, and MATLAB arrays start with index 1.
Réponse acceptée
Voss
le 7 Avr 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!