Search code examples
arraysmatlabmatrixsubmatrix

A subset of 3 dimensional matrix in Matlab


Lets assume we have a 3 dimensional matrix A and X_IND = 4:8 and Y_IND = f(X_IND). f is a function like 2*x^2+1. How I can extract following vector out of A:

a = A(X_IND,Y_IND,3)

However, above equation in MATLAB leads to a matrix while the result should be an array since Y_IND is function of X_IND.


Solution

  • Use sub2ind to build a linear index. Here's an example:

    >> A = randi(9,2,3,3)
    A(:,:,1) =
         6     8     8
         5     2     7
    A(:,:,2) =
         8     7     9
         8     7     2
    A(:,:,3) =
         8     9     8
         2     4     8
    
    >> X_IND = [1 2]; 
    >> Y_IND = X_IND + 1;
    >> Z_IND = 3;
    
    >> Z_IND = repmat(3, size(X_IND)); %// all indices should have the same size
    
    >> ind = sub2ind(size(A), X_IND, Y_IND, Z_IND); %// build linear index
    
    >> A(ind)
    ans =
         9     8