![]() |
VOOZH | about |
In this article, we will see the swapping of elements into a matrix in MATLAB. Different methods are illustrated below:
In this method, we are simply changing the elements of particular rows and columns in the specified rows and columns respectively.
Example 1:
Output:
A = 5 10 15 20 A = 15 10 5 20
Example 2:
Output:
A = 5 10 15 20 25 30 35 40 45 A = 5 10 15 35 25 30 20 40 45 A = 5 25 15 35 10 30 20 40 45
In this approach, we are using the combination of randperm() and size() functions.
The randperm() function is used for the random permutation of integers of the specified matrix.
Syntax:
randperm(A)
Parameters: This function accepts a parameter.
The size() function is used to return the size of each dimension of the specified array "X" or the size of the specified matrix "X".
Syntax:
size(X)
[m,n] = size(X)
size(X,dim)
[d1,d2,d3,...,dn] = size(X)
Here,
size(X) returns the size of each dimension of the specified array "X" in a vector d with ndims(X) elements.
[m,n] = size(X) returns the size of the specified matrix "X" in the separate variables m and n.
size(X,dim) returns the size of the dimension of "X" specified by scalar dim.
[d1,d2,d3,...,dn] = size(X) returns the sizes of the first n dimensions of the specified array "X" in separate variables.
Parameters: This function accepts two parameters, which are illustrated below:
Example 1:
Output:
random = 7 8 9 1 2 3 4 5 6
Example 2:
Output:
random = 3 1 2 6 4 5 9 7 8