3d matrix element extraction

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 Commento

Martin Siu
Martin Siu il 19 Nov 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

Accedi per commentare.

 Risposta accettata

dpb
dpb il 19 Nov 2016
Modificato: dpb il 19 Nov 2016
[~,~,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 Commenti

Martin Siu
Martin Siu il 19 Nov 2016
Thank you!
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.
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 il 20 Nov 2016
Modificato: dpb il 20 Nov 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... :)

Accedi per commentare.

Più risposte (0)

Richiesto:

il 19 Nov 2016

Modificato:

dpb
il 20 Nov 2016

Community Treasure Hunt

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

Start Hunting!

Translated by