Michael L.
Michael L.

Reputation: 473

How to force a vector to be row vector?

What is the most simple way to force any vector to be a row vector?

I wish to have some function that transforms column vector to a row vector, and leaves a row vector unchanged. For example:

A= [1 2 3];
RowIt(A)

will output a row vector:

1 2 3

and:

B= [1; 2; 3];
RowIt(B) 

will output a row vector:

1 2 3

What is the most simple way to do it?

Upvotes: 6

Views: 6293

Answers (3)

beesleep
beesleep

Reputation: 1362

Just reshape the matrix/verctor to a single row :

v = reshape(v,1, [])

It will also leave a vector of the right shape unchanged.

If you go to the documentation on reshape, the 1 means 1 row, and the [] means as many columns as needed given the size of v.

The full function:

function v = RowIt(v)
    v = reshape(v,1,[]);
end

Comparing with @Adriaan answer

Reshape version:

v = rand(5000*5000, 1);
tic;
for i=1:100000
    b = reshape(v,1, []);
end
toc
Elapsed time is 0.347047 seconds.

(:).' version: this answer

v = rand(5000*5000, 1);
tic
for i=1:100000
    b = v(:).';
end
toc
Elapsed time is 0.082710 seconds

So @Adriaan's solution is clearly faster, probably due to function call overload cost. You must know that no data is copied during this operation, except if you modify it (MATLAB copy on modify), so it is really fast anyway.

The advantage is for reshape when you need to customize things, like:

a = rand(10, 10)
size(reshape(a, 2,[]))

ans =

2    50

Upvotes: 9

Adriaan
Adriaan

Reputation: 18177

To get any vector to be a row vector simply first force it to be a column vector, then transpose it:

A = rand(3,1);
B = A(:).'; % (:) forces it to unwrap along columns, .' transposes

A row vector gets unwrapped to a column vector and then transposed to a row vector again, and a column vector gets unwrapped to a column vector (thus doesn't change) and then gets transposed to a row vector.

Note that any N-dimensional matrix will be forced into a row vector this way due to column unwrapping:

A = rand(3,3,3,3);
B = A(:).'; % 81 element row vector

Upvotes: 13

Jack
Jack

Reputation: 6168

Transpose:

A= [1 2 3];
A.'

will output

1
2
3

You can also write:

transpose(A)

https://www.mathworks.com/help/matlab/ref/transpose.html

Upvotes: -4

Related Questions