lettura simple

Changing the number of rows and columns of a matrix in Matlab

In this lesson, I'll show you how to change the number of rows and/or columns of a matrix in Matlab while keeping the total number of elements in the matrix unchanged.

Here's a practical example.

Create a rectangular matrix 3x2 with three rows and two columns.

>> M = [ 1 2 ; 3 4 ; 5 6 ]
M =
1 2
3 4
5 6

Now type the function reshape(M,2,3) to transform the matrix into a rectangular matrix 2x3 with two rows and three columns.

>> reshape(M,2,3)
ans =
1 5 4
3 2 6

The target matrix must have the same number of elements.

So, you can also transform the initial matrix into a row vector by typing reshape(M,1,6)

>> reshape(M,1,6)
ans =
1 3 5 2 4 6

or into a column vector by typing reshape(M,6,1)

>> reshape(M,6,1)
ans =
1
3
5
2
4
6

In all cases, the number of elements remains unchanged.

Note. In fact, a vector is a special matrix with only one row (1x6) or one column (6x1).

You can also transform a vector into a matrix.

For example, create a vector composed of eight elements.

>> v = [ 1 2 3 4 5 6 7 8 ]
v =
1 2 3 4 5 6 7 8

Then transform the vector into a matrix 2x4 with two rows and four columns by typing reshape(v,2,4).

>> reshape(v, 2, 4)
ans =
1 3 5 7
2 4 6 8

The matrix has the same number of elements as the vector.

Alternatively, you can transform the vector into a matrix 4x2 by typing reshape(v,4,2).

>> reshape(v, 4, 2)
ans =
1 5
2 6
3 7
4 8

This way you can convert any vector into a matrix and vice versa, as long as the total number of elements remains the same.

The reshape command generates an error when the number of elements is different.

For example, you cannot convert a 4x2 matrix into a 3x3 matrix because the first matrix has 8 elements while the second matrix has 9 elements.

In this case, the reshape() command returns an error message.

>> reshape(M,3,3)
Error using reshape
Number of elements must not change. Use [ ] as one of the size inputs to automatically calculate the appropriate size for that dimension




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin