effective way of transformation from 2D to 1D vect

2019-09-16 08:12发布

i want to create 1D vector in matlab from given matrix,for this i have implemented following algorithm ,which use trivial way

% create   one dimensional vector from 2D  matrix
function [x]=one_dimensional(b,m,n) 
 k=1;
 for i=1:m 
     for  t=1:n
         x(k)=b(i,t);
         k=k+1;
     end
 end
  x;
end

when i run it using following example,it seems to do it's task fine

b=[2 1 3;4 2 3;1 5 4]

b =

     2     1     3
     4     2     3
     1     5     4

>> one_dimensional(b,3,3)

ans =

     2     1     3     4     2     3     1     5     4

but generally i know that,arrays are not good way to use in matlab,because it's performance,so what should be effective way for transformation matrix into row/column vector?i am just care about performance.thanks very much

1条回答
欢心
2楼-- · 2019-09-16 08:29

You can use the (:) operator...But it works on columns not rows so you need to transpose using the 'operator before , for example:

b=b.';
b(:)'

ans=
   2     1     3     4     2     3     1     5     4

and I transposed again to get a row output (otherwise it'll the same vector only in column form)

or also, this is an option (probably a slower one):

reshape(b.',1,[])
查看更多
登录 后发表回答