Search code examples
matlabmatrixvectordata-conversion

converting values of a matrix of order (NxN) to a vector with order (NxN, 1)


I have a matrix let's say A with NxN order (here, 3x3) given by:

A = | a b c|
    | d e f|
    | g h i|

And I want to convert this matrix into a single vector of order [NxN, 1] (here, 9x1) given by:

P = |a|
    |b|
    |.|
    |.|
    |.|
    |i|

So, right now what I'm using for converting it for a larger order of matrices & vectors is:

% A is a given matrix with some arbitrary values of order (N,M)

P = zeros(N*M, 1);
  
for i = 1:N
    for j = 1:M
       P((i-1)*M + j, 1) = A(i,j)
    end 
end 

But I am still getting some values in the vector P that is having values as zeros. I'm not sure what am I doing wrong. Any suggestions, what should be the correction in the code? I also feel there is a possibility that some values are getting overlapped over some already filled data fields in the vector P.


Solution

  • You can always simply unroll the vector

    P=A(:);
    

    And of course, of you don't like this ordering

    Aaux=A.'; %transpose first.
    P=Aaux(:);