Generate Row & column vector from Any Matrix in Matlab

Converting from a matrix to its equivalent row or column vector is very easy in MATLAB. This is particularly useful in communication where the data or here matrix has to be send serially. The matrix will be converted to a n x 1 or 1 x n vector & sent element by element. This process is often called vectorization. It has many applications in Sparse Signal Recovery & image processing also.

Suppose you have a random 5 x 5 matrix generated by rand(5,5); function  stored in variable 'x'.
In our case it is,
>> x=rand(5,5)

>> x=
0.3197    0.1639    0.6798    0.0195    0.9360
0.6711    0.4944    0.3285    0.6075    0.4886
0.5240    0.7647    0.5383    0.5388    0.6976
0.6078    0.3008    0.8378    0.2263    0.5166
0.7603    0.8389    0.2430    0.9199    0.2852

Now to convert the matrix 'x' to a column vector we just need one command.
i.e.,
>> y=x(:) %suppose we store the resultant column vector in variable named 'y'
That will throw the result,
>> y =
0.3197
0.6711
0.5240
0.6078
0.7603
0.1639
0.4944
0.7647
0.3008
0.8389
0.6798
0.3285
0.5383
0.8378
0.2430
0.0195
0.6075
0.5388
0.2263
0.9199
0.9360
0.4886
0.6976
0.5166
0.2852

& >> size(y)=  [25   1] %column vector

Now to convert the matrix 'x' to a row vector we need only slight modification of previous command command.
i.e.,
>> z=x(:)' %suppose we store the resultant column vector in variable named 'z'

That will throw the result,
>>  z =
Columns 1 through 9
0.3197    0.6711    0.5240    0.6078    0.7603    0.1639    0.4944    0.7647    0.3008

Columns 10 through 18
0.8389    0.6798    0.3285    0.5383    0.8378    0.2430    0.0195    0.6075    0.5388

Columns 19 through 25
0.2263    0.9199    0.9360    0.4886    0.6976    0.5166    0.2852

& >> size(z)=  [1    25] %row vector

NOTE: It might be an important point to note that MATLAB while vectorization (or while converting matrix to a row or column vector) reads the elements column wise not row wise, which we usually learn in our schools. For doing that in row wise ways you must take first the transpose of the original matrix & then perform above operations.

i.e.,
x=rand(5,5)
b=x'; %taking transpose to convert columns into rows & storing in a new variable 'b'

y=b(:); %Column vector when read column wise of original 'x' & stored in 'y'

z=b(:)'; %Column vector when read column wise of original 'x' & stored in 'z'