interesting matrix indexing question without for loops

1 visualización (últimos 30 días)
Chris Hooper
Chris Hooper el 2 de Oct. de 2018
Comentada: Chris Hooper el 3 de Oct. de 2018
size(matrixA)=[b,n,m]
size(matrixB)=[n,m]
how can I create
matrixC(i,j)=matrixA(matrixB(i,j),i,j)
without using for-loops? What is this kind of indexing called? Thanks!

Respuesta aceptada

Stephen23
Stephen23 el 3 de Oct. de 2018
Editada: Stephen23 el 3 de Oct. de 2018
Use sub2ind to get the linear indices:
A = reshape(1:6*3*2,6,3,2);
B = [6,1;4,3,;5,2];
% Solution with loops:
for ii = 1:size(B,1)
for jj = 1:size(B,2)
C(ii,jj) = A(B(ii,jj),ii,jj);
end
end
% Solution with SUB2IND:
S = size(B);
[I,J] = ndgrid(1:S(1),1:S(2));
X = sub2ind(size(A),B,I,J);
D = A(X)
% Compare:
isequal(C,D)
  1 comentario
Chris Hooper
Chris Hooper el 3 de Oct. de 2018
Stephen you're awesome thanks! I knew there was something like that... it's been a while!

Iniciar sesión para comentar.

Más respuestas (1)

Bruno Luong
Bruno Luong el 3 de Oct. de 2018
Editada: Bruno Luong el 3 de Oct. de 2018
C = A(B+reshape(0:numel(B)-1,size(B))*size(A,1))
  1 comentario
Chris Hooper
Chris Hooper el 3 de Oct. de 2018
Awesome I'll check this one, cannot even wrap my head around it!!

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by