Filter löschen
Filter löschen

Picking values from n-d array along 3rd dimension

1 Ansicht (letzte 30 Tage)
Pal
Pal am 11 Jun. 2013
Hi,
Suppose I have A, an m x n x q array with large integer values.
I have B, an m x n array of integer values in the range of 1:q.
I'd like to pick values from A along the 3rd dimension, so that I obtain C, an m x n array in which for every subscript pair (i,j), m>i>1, n>j>1 the following is true:
x = B(i,j)
C(i,j) = A(i,j,x)
Is there an efficient, loop-free way of doing this?
Many thanks,

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 11 Jun. 2013
Bearbeitet: Andrei Bobrov am 11 Jun. 2013
[ii,jj] = ndgrid(1:m,1:n);
ijk = sub2ind(size(A),ii,jj,B);
C = A(ijk);

Weitere Antworten (2)

Roger Stafford
Roger Stafford am 11 Jun. 2013
C = A((1:m*n)'+m*n*(B(:)-1));
C = reshape(C,m,n);
  3 Kommentare
Pal
Pal am 11 Jun. 2013
This is 2X faster than the accepted answer. Thanks!
Roger Stafford
Roger Stafford am 11 Jun. 2013
A(reshape(1-m*n:0,m,[])+m*n*B)

Melden Sie sich an, um zu kommentieren.


David Sanchez
David Sanchez am 11 Jun. 2013
You can assign the value of C without referencing (i,j):
x = B(i,j);
C = A(:,:,x);
And you will have for all i, j that C(i,j) = A(i,j,x)
  1 Kommentar
Pal
Pal am 11 Jun. 2013
Could you elaborate, please? If I write
C = A(:,:,B),
the answer is an m x n x numel(B) array, which is incorrect. What do you mean by 'without referencing (i,j)'? B is not constant.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by