Methods to Flip a Vector in MATLAB
There are two main ways to flip a vector in MATLAB: using the flip function and indexing.
Using the flip Function
The flip function reverses the vector element’s order. For example, if x = [1 2 3], then flip(x) returns [3 2 1]. The flip function can also be used to flip matrices along different dimensions.
Using Indexing
Another way to flip a vector in MATLAB is to use indexing. For example, if x = [1 2 3], then x(end:-1:1) returns [3 2 1]. This method uses the colon operator (:) with a negative step size to reverse the order of elements in the vector.
Example: Flipping a Vector in MATLAB
Here’s an example that shows how to flip a vector in MATLAB using flip() function:
x = [1 2 3]
% Flip the vector using the flip function
y = flip(x)
This code creates a row vector x with three elements and then flips it using the flip function. The output is stored in vector y.
Below example flip a vector in MATLAB using indexing:
x = [1 2 3]
% Flip the vector using indexing
z = x(end:-1:1)
This code flips a row vector using the indexing and stores the result in vector z. The resulting vectors y and z are both equal to [3 2 1].
Flip Row Vector Using fliplr Function
The function fliplr(A) reverses the order of columns in matrix A by flipping it horizontally. This function flips the array left to right. If A is a row vector, the function reverses the order of its elements. If the defined vector A is a column vector, it remains the same. For multi-dimensional arrays, fliplr works by flipping the columns of each slice formed by the first and second dimensions.
Syntax
Examples
First, we will create a new row vector.
Next, we will use the fliplr MATLAB function to flip the elements of A horizontally.
The new matrix B has order reversed compared to A.
Flip Column Vector Using flipud Function
The function flipud(A) flips the order of rows in matrix A by flipping it vertically. This function flips the array up to down. If A is a column vector, the function reverses the order of its elements. If A is a row vector, it remains the same. For multi-dimensional arrays, flipud operates by flipping the rows of each layer formed by the first and second dimensions.
Syntax
Example
First, we will define a new column vector.
Now using the flipud function we will flip elements of A vertically.
In output, we can see the order of both vectors is reversed.
Conclusion
In this article, we discussed how to flip a vector in MATLAB using two different methods: the flip function and indexing. Using the flip function, we just have to pass the name of the vector as the argument of this function. Further, we also covered the two MATLAB functions fliplr and flipud to flip the vector row and column respectively. Read about all these methods of flipping vectors in this article.