effective way of transformation from 2D to 1D vector

人走茶凉 提交于 2019-12-25 16:57:20

问题


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:


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,[])


来源:https://stackoverflow.com/questions/15585480/effective-way-of-transformation-from-2d-to-1d-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!