Matlab

How to Turn a Matrix into a Row Vector in MATLAB?

Matrices as well as vectors are the building blocks of MATLAB and are used in various science and engineering applications. Sometimes we require to change the dimension of a matrix or a vector, such as can transform a matrix into a row or column vector and vice versa. Turning a matrix into a row vector is useful because it is easy to manipulate a row vector instead of a matrix.

This blog is going to explore how to convert a matrix into a row vector in MATLAB.

How to Transform a Matrix into a Row Vector in MATLAB?

We can transform the matrix into the row vector in MATLAB utilizing the reshape() function. The reshape() is a built-in function in MATLAB that enables us to alter an array’s dimension. This function is used for converting a matrix into a row vector. This function accepts two arguments as input and returns a row vector that is the transformation of the provided matrix and contains all elements of the provided matrix.

Syntax

To convert a matrix into a row vector, the reshape() function uses the following syntax:

vect = reshape(A,sz)

Here:

The function vect = reshape(A,sz) yields to turn a matrix into a row vector having specified size sz. The matrix A’s cardinality must be the same as the size of the row vector. For example, if the given matrix A’s dimension is 5-by-2 then the sz should be 1-by-10.

Examples

In this section, we will understand the working of the reshape() function to convert a matrix into a row vector by performing some examples in MATLAB.

Example 1: How to Convert a Square Matrix into the Row Vector Utilizing the reshape() Function?

The given example creates a square matrix having size n = 3. After that, it uses the reshape() function to convert this matrix into a row vector having size 1-by-9.

A = magic(3);

vect = reshape(A,1,9)

Example 2: How to Convert a Rectangular Matrix into the Row Vector Utilizing the reshape() Function?

In the given MATLAB code, we create a rectangular matrix having a size of 2-by-3. After that, we use the reshape() function to convert this matrix into a row vector having size 1-by-6.

A = ones(2,3);

vect = reshape(A,1,6)

Conclusion


MATLAB is a beneficial programming language that allows us to perform various matrix operations. It facilitates us to convert a matrix into a row vector using the built-in reshape() function. This function accepts a matrix and the size of the obtained row vector as arguments and returns a row vector having the cardinality the same as the given matrix. This guide has discovered how to transform a matrix into a row vector in MATLAB using the reshape() function.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.