Index in position 2 is invalid. Array indices must be positive integers or logical values.
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Brianna Miranda
el 7 de Abr. de 2022
Respondida: Voss
el 7 de Abr. de 2022
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 comentario
Torsten
el 7 de Abr. de 2022
round(N*IX) and round(N*IY) can also produce 0 as a result, and MATLAB arrays start with index 1.
Respuesta aceptada
Voss
el 7 de Abr. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!