How do I resize a matrix in MATLAB?

42,386

Solution 1

reshape is of course the proper solution, as stated by @gnovice.

A nice feature of reshape is that it allows this:

A = 1:12;
B = reshape(A,4,[]);
B =
     1     5     9
     2     6    10
     3     7    11
     4     8    12

So if you don't know how many columns there will be, reshape will compute it for you. Likewise, reshape will fill in the number of rows, if you leave that out.

C = reshape(A,[],4)
C =
     1     4     7    10
     2     5     8    11
     3     6     9    12

Solution 2

Try the RESHAPE function:

A = (1-by-12 matrix);
B = reshape(A,4,3);

Note that the matrix B will be filled with elements from A in a columnwise fashion (i.e. columns will be filled from top to bottom, moving left to right).

Example:

>> A = 1:12;
>> B = reshape(A,4,3)

B =

     1     5     9
     2     6    10
     3     7    11
     4     8    12

Solution 3

to extend gnovice's solution:

If you need a different order of matrix construction, use transpose (the ' operator) or permute() to change the dimension ordering after you have called reshape().

Share:
42,386
bastibe
Author by

bastibe

I am an scientist / engineer with specialization in signal processing and audio technology.

Updated on July 19, 2022

Comments

  • bastibe
    bastibe over 1 year

    Suppose I had a 1-by-12 matrix and I wanted to resize it to a 4-by-3 matrix. How could I do this?

    My current solution is kind of ugly:

    for n = 1:(length(mat)/3)
        out(n,1:3) = mat( ((n-1)*3 + 1):((n-1)*3 + 3) );
    end
    

    Is there a better way to do this?

  • AnnaR
    AnnaR over 14 years
    Note that the reshape returns an error if A doesn't have exactly 4*3 elements.
  • gnovice
    gnovice over 14 years
    Yes, that is the normal expected behavior of RESHAPE.
  • gnovice
    gnovice over 14 years
    +1: Nice! I actually never noticed that before. I guess I never had to use it.
  • Nadeeshani Jayathilake
    Nadeeshani Jayathilake over 12 years
    Can't we tell RESHAPE to add zeros if there are no exactly 4*3 elements? I meant if there are less than 12 elements.
  • gnovice
    gnovice over 12 years
    @Nadeeshani: No, but you can do this instead: A = 1:11; B = zeros(4,3); B(1:numel(A)) = A;
  • Parth Sane
    Parth Sane almost 7 years
    @gnovice A = 1:11; B = zeros(4,3); B(1:numel(A)) = A; Does this columnwise?
  • gnovice
    gnovice almost 7 years
    @Boggartfly: Yes, that will fill B columnwise. If you want to fill rowwise, I would do this: A = 1:11; B = zeros(3,4); B(1:numel(A)) = A; B = B.';