How to extract 3D matrix from N-D matrix?

I am working on 5D matrix configured as follow :

``````[nf,nx,ny,np,nz]=size(D);
``````

such

``````nf=301;
nx=12;
ny=12;
np=12;
nz=12;
``````

I need to extract two matrices from this 5D matrix D :

• The first `A`, such `[nf,nx,ny]=size(A);`
• The second `B`, such `[nf,np,nz]=size(B);`

Is there any MATLAB codes to extract these two matrices from `D` ?

• There are 144 possibilities for A and 144 possibilities for B that can be obtained through simple indexing. Which are you looking for? – Mad Physicist Jun 12 at 13:07
• Dear Mad Physicist, I need a code that would allow me to extract B and A whatever the possibility but without changing the nature of the data. Thanks – YAPO Jun 12 at 13:27
• If you want to extract a square on a chessboard you have to select a square, for example C5. Your code cannot guess. – obchardon Jun 12 at 13:40

To do this, you'll need to choose specific subscripted index values for two dimensions, extract the data from your multidimensional array, then collapse the resulting dimensions of length 1 using the `squeeze` function as needed. Here's how it would work for `A` and `B`:

``````pIndex = 2;  % Second index of dimension 4
zIndex = 3;  % Third index of dimension 5
A = D(:, :, :, pIndex, zIndex);  % Don't need squeeze because they
%   are the trailing dimensions

xIndex = 1;   % First index of dimension 2
yIndex = 12;  % Last index of dimension 3
B = squeeze(D(:, xIndex, yIndex, :, :));
``````

Note that using a colon as an index will include all subscripts from that dimension.

• Thanks Dear for answer. It works very well as I expected. thank ! – YAPO Jun 12 at 14:32
• @YAPO: Happy to help. Don't forget that you can mark an answer as accepted when it solves your problem. – gnovice Jun 12 at 14:38