lettura simple

Converting a Matrix to a Vector in Matlab

In this guide, I'll show you how to convert a matrix to a vector when using Matlab.

To illustrate this, consider the following practical example.

Create a rectangular 2x3 matrix with two rows and three columns.

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

Now type the command M(:) to transform the matrix into a column vector.

>> M(:)

When you enter this command, Matlab arranges all the elements of the matrix into a column vector, i.e., vertically.

ans =
1
4
2
5
3
6

The number of elements remains the same. As many elements as the matrix has, so many elements the column vector has.

How to obtain a row vector?

To convert the matrix to a row vector, type M(:)' with the transpose symbol (the apostrophe) at the end of the command.

>> M(:)'

In this case, Matlab arranges all the elements of the matrix into a row vector, i.e., horizontally.

ans =
1 4 2 5 3 6




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin