Given a 10x10x3 matrix, I would like to extract the 3rd dimension for the 5 specific rows and columns, for example:
row indices a=[1 3 5 7 9]
column indices b=[2 4 6 8 10]
And store the result in a 5x3 matrix. How can I achieve this?

1 comentario

Martin Siu
Martin Siu el 19 de Nov. de 2016
PS - each row index correspond to each column index, i.e. [1 2] [3 4] etc
PPS - can't use for loop: it will take too long to run in the actual data

Iniciar sesión para comentar.

 Respuesta aceptada

dpb
dpb el 19 de Nov. de 2016
Editada: dpb el 19 de Nov. de 2016

0 votos

[~,~,p]=size(m); % array depth for generality
ix=sub2ind(size(m),repmat(a,1,p),repmat(b,1,p),repmat(1:p,1,length(a))); % doc sub2ind for details
subm=m(ix);
reshape and/or reorder as desired; above will be vector of length p*length(a) in order as in the list of subscript vectors.
ADDENDUM
If you preallocate, I'd expect a loop to not be terribly slow, either.

4 comentarios

Martin Siu
Martin Siu el 19 de Nov. de 2016
Thank you!
dpb
dpb el 20 de Nov. de 2016
BTW, if it matters, you'll note the caveat before on order--the above selects by the order in a,b for each plane successively...to pick out by [a(i),b(i),:] need to generate the subscript index in that order to pass to sub2ind instead of just concatenating the planes at the end of the copies of a, b --
ix=sub2ind(size(m), ...
reshape(repmat(a,p,1),[],1), ...
reshape(repmat(b,p,1),[],1), ...
repmat([1:p].',length(a),1));
To see the difference create the array from the arguments to ind2sub (without the size, of course) and see the sequence difference.
Image Analyst
Image Analyst el 20 de Nov. de 2016
A for loop should be pretty fast. If it's not fast enough for your 10x10x3 array, you'd better lighten up on the caffeine!
dpb
dpb el 20 de Nov. de 2016
Editada: dpb el 20 de Nov. de 2016
As noted in my original answer, if preallocate, I'd agree...OP did note, however, " it will take too long to run in the actual data" so I presume the real case is quite a lot larger. Of course, with today's CPUs what is "really large" is also a major departure from what we were used to thinking of even 10 yr ago, what more 30 or 40 when I was a (at least moderately) young pup... :)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 19 de Nov. de 2016

Editada:

dpb
el 20 de Nov. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by