How to Permute the Rows and Columns in a Matrix on MATLAB?
Last Updated :
27 Jan, 2022
In this article, we will discuss how to find the permutation of the rows and columns in a Matrix with the help of multiple approaches
Method 1
In this approach, we are simply permuting the rows and columns of the matrix in the specified format of rows and columns respectively. For column permutation, we take an example of a 3*3 matrix being permuted in such a way that its first column becomes the second one, the second becomes the third one and lastly, the third becomes the first column.
Example 1:
Matlab
A = [1 2 3
4 5 6
7 8 9]
index = [3 1 2]
B = A(:, index)
|
Output:
A =
1 2 3
4 5 6
7 8 9
index =
3 1 2
B =
3 1 2
6 4 5
9 7 8
Example 2:
Matlab
A = [1 2 3
4 5 6
7 8 9]
index = [3 1 2]
B = A(index, 🙂
|
Output:
A =
1 2 3
4 5 6
7 8 9
index =
3 1 2
B =
7 8 9
1 2 3
4 5 6
Method 2
The perms() function returns a matrix that contains all the possible permutations of the elements of the specified vector “v” in reverse lexicographic order. Here each row of the returned matrix contains a different permutation of the “n” elements of the specified vector “v”. The returned matrix has the same data type as the given vector “v” and has n! rows and n columns.
Syntax:
perms(v)
Parameters: This function accepts a parameter which is illustrated below:
- v: This is the specified vector containing the “n” number of elements.
Return Value: It returns a matrix that contains all the possible permutations of the elements of the specified vector “v” in reverse lexicographic order.
Example 1:
Matlab
vector = [1 2 3];
P = perms(vector)
|
Output:
P =
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
Example 2:
Matlab
vector = [1+2i 3+4i 5+6i];
P = perms(vector)
|
Output:
P =
5 + 6i 3 + 4i 1 + 2i
5 + 6i 1 + 2i 3 + 4i
3 + 4i 5 + 6i 1 + 2i
3 + 4i 1 + 2i 5 + 6i
1 + 2i 5 + 6i 3 + 4i
1 + 2i 3 + 4i 5 + 6i
Method 3
The permute() function rearranges the dimensions of the specified array in the order specified by the vector dimorder.
Syntax:
permute(A, dimorder)
Parameters: This function accepts two parameters, which are illustrated below:
- A: This is the specified array matrix.
- dimorder: This is the specified vector order in which permutation is being done.
Return Value: It returns the permuted matrix.
Example 1:
Matlab
A = rand(2, 3)
B = permute(A, [2 1])
|
Output:
A =
0.32773 0.12633 0.67752
0.26285 0.91283 0.42994
B =
0.32773 0.26285
0.12633 0.91283
0.67752 0.42994
Example 2:
Matlab
A = rand(3, 3, 2)
B = permute(A, [2 3 1])
|
Output:
A =
ans(:,:,1) =
0.53364 0.65671 0.32496
0.82471 0.36042 0.31604
0.82714 0.84231 0.70248
ans(:,:,2) =
0.424538 0.498572 0.972245
0.069400 0.799598 0.754885
0.722046 0.807107 0.392804
B =
ans(:,:,1) =
0.53364 0.42454
0.65671 0.49857
0.32496 0.97224
ans(:,:,2) =
0.824706 0.069400
0.360418 0.799598
0.316038 0.754885
ans(:,:,3) =
0.82714 0.72205
0.84231 0.80711
0.70248 0.39280
Share your thoughts in the comments
Please Login to comment...