How do you concatenate the rows of a matrix into a vector?

For an m-by-m (square) array, how do you concatenate all the rows into a column vector with size m^2 ?

Answers


There are a couple of different ways you can collapse your matrix into a vector, depending upon how you want the contents of your matrix to fill that vector. Here are two examples, one using the function reshape (after first transposing the matrix) and one using the colon syntax (:):

>> M = [1 2 3; 4 5 6; 7 8 9];    % Sample matrix
>> vector = reshape(M.', [], 1)  % Collect the row contents into a column vector

vector =

     1
     2
     3
     4
     5
     6
     7
     8
     9

>> vector = M(:)  % Collect the column contents into a column vector

vector =

     1
     4
     7
     2
     5
     8
     3
     6
     9

A very important note in changing a matrix to a vector is that , MATLAB produce the output vector form the columns of the matrix, if you use A(:)

for example :

A = [1 2 3 ; 4 5 6]

B = A (:)

B = [1 4 2 5 3 6]

You can see the direction of changing in the following image.


Need Your Help

Symfony 2 EntityManager injection in service

php symfony dependency-injection

I've created my own service and I need to inject doctrine EntityManager, but I don't see that __construct() is called on my service, and injection doesn't work.

Looking for a practical approach to sandboxing .NET plugins

.net mef sandbox code-access-security maf

I am looking for a simple and secure way to access plugins from a .NET application. Although I imagine that this is a very common requirement, I am struggling to find anything that meets all my nee...