user3240368
user3240368

Reputation: 119

matlab - matrix to vector

I have (n x n) matrix in Matlab. For example(n=3):

A=[1,2,3; 4,5,6; 1,9,9]

I want save this matrix to vector (or array) B, but rows should be first. Output:

A=[1,2,3,4,5,6,1,9,9]

Thank you

Upvotes: 0

Views: 1777

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

There are several ways:

  1. Use reshape:

    B = reshape(A.',1,[]);
    
  2. Use vec2mat from the Communications Toolbox:

    B = vec2mat(A,numel(A));
    
  3. Transpose A and then use linear indexing:

    A = A.';
    B = A(:).'
    

Upvotes: 1

herohuyongtao
herohuyongtao

Reputation: 50657

Besides @LuisMendo's answer using reshape or vec2mat, you can also use

Method 1:

B = A';
C = B(:)' % final result

Method 2:

C = subsref(A.', substruct('()', {':'})).'  % final result

Upvotes: 0

Related Questions