Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Matrix to Vector row-wise

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

like image 953
tim Avatar asked Dec 15 '13 14:12

tim


People also ask

How do I convert a matrix to a vector in MATLAB?

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.

How do you make a row vector in MATLAB?

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.

How do you access a row of a matrix in MATLAB?

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.


1 Answers

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.

like image 69
Shai Avatar answered Sep 29 '22 10:09

Shai