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
Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.
In MATLAB you can create a row vector using square brackets [ ]. Elements of the vector may be separated either by one or more blanks or a comma ,. Create a row vector x with elements x1 = 1, x2 = -2 and x3 = 5. Square brackets are use to create a row vector.
For example, to access a single element of a matrix, specify the row number followed by the column number of the element. e is the element in the 3,2 position (third row, second column) of A . You can also reference multiple elements at a time by specifying their indices in a vector.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With