Reshape 3d matrix to 2d matrix

前端 未结 3 1040
栀梦
栀梦 2020-12-01 18:21

I have a 3d matrix (n-by-m-by-t) in MATLAB representing n-by-m measurements in a grid over a period of time. I would like to have a 2d matrix, wher

3条回答
  •  青春惊慌失措
    2020-12-01 18:50

    Reshape is of course the standard solution to reshaping an array. (What else would they call it?) There are still a few tricks to uncover.

    First of all, the simplest way to turn an array of size [n,m,p] into an array of size [n*m,p]?

    B = reshape(A,n*m,p);
    

    But better is this:

    B = reshape(A,[],p);
    

    If you leave one of the arguments to reshape empty, then reshape computes the size for you! Be careful, if you try this and the size of A does not conform, then you will get an error. Thus:

    reshape(magic(3),[],2)
    ??? Error using ==> reshape
    Product of known dimensions, 2, not divisible into total number of elements, 9.
    

    Logically, we cannot create an array of with two columns from something that has 9 elements in it. I did put a function called wreshape on the MATLAB Central exchange that would pad as necessary to do this operation with no error generated.

    Of course, you can always use tricks like

    B = A(:);
    

    to create a vector directly from a matrix. This is equivalent to the form

    B=reshape(A,[],1);
    

提交回复
热议问题