MATLAB: Matrix to Vector row
How to turn a matrix into a vector row-wise efficiently. Example:
>> a = [1 2; 3 4]
a =
1 2
3 4
the (:)
notation gives me:
>> a(:)
ans =
1
3
2
4
but I want to get the result as this:
>> b = a'; b(:)
ans =
1
2
3
4
The transposition and the additional var-assignment makes it much slower. I could do it without the assignment via reshape like this:
>> reshape(a',4,1)
ans =
1
2
3
4
which is a very small bit faster then the previous one, see the bench:
runs = 1000;
num = 1000;
A = rand(num);
times = zeros(runs, 2);
for i = 1:runs
tic
x = A';
x = x(:);
t1 = toc;
x = reshape(A',size(A,1)*size(A,2),1);
t2 = toc-t1;
times(i,:) = [t1 t2];
end
format shortG
mt = mean(times)
mt =
0.0037877 0.0037699
If I'm leaving away the transposition it would be very very much faster and the (:)
syntax would be >100% faster:
runs = 100;
num = 5000;
A = rand(num);
times = zeros(runs, 2);
for i = 1:runs
tic
x = A(:);
t1 = toc;
x = reshape(A,size(A,1)*size(A,2),1);
t2 = toc-t1;
times(i,:) = [t1 t2];
end
format shortG
mt = mean(times)
mt =
3.307e-07 8.8382e-07
that's why I'm asking if there's such a nice syntax like (:)
but to get it row-wise to a vector!? Thanks
Think about how the elements are organized in memory. Their "natural" order is column wise. Thus A(:)
simply changes the header of the matrix but does not need to change enything in the memory storing the elements themselfs. However, when you transpose A
, you need to re-arrange the elements in memory (copying and swapping) and this takes time.
上一篇: 查询所有公开的facebook信息
下一篇: MATLAB:矩阵到矢量行