Search code examples
matlabmultidimensional-arraycrop

How to crop matrix of any number of dimensions in Matlab?


Suppose I have 4D matrix:

>> A=1:(3*4*5*6);
>> A=reshape(A,3,4,5,6);

And now I want to cut given number of rows and columns (or any given chunks at known dimensions).

If I would know it's 4D I would write:

>> A1=A(1:2,1:3,:,:);

But how to write universally for any given number of dimensions?

The following gives something different:

>> A2=A(1:2,1:3,:);

And the following gives an error:

>> A2=A;
>> A2(3:3,4:4)=[];

Solution

  • It is possible to generate a code with general number of dimension of A using the second form of indexing you used and reshape function. Here there is an example:

    Asize = [3,4,2,6,4]; %Initialization of A, not seen by the rest of the code
    A = rand(Asize);
    
    %% This part of the code can operate for any matrix A
    I = 1:2;
    J = 3:4;
    A1 = A(I,J,:);
    NewSize = size(A);
    NewSize(1) = length(I);
    NewSize(2) = length(J);
    A2 = reshape(A1,NewSize);
    

    A2 will be your cropped matrix. It works for any Asize you choose.