Method  2: By using randperm() and size() functions

 In this approach, we are using the combination of randperm() and size() functions. 

 randperm()

The randperm() function is used for the random permutation of integers of the specified matrix.

Syntax: 

randperm(A)

Parameters: This function accepts a parameter.

  • A: This is the specified matrix.

size()

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:

  • X: It is the specified array or matrix or dimension.
  • dim: It is the scalar value for the specified dimension “X”

Example 1: 

Matlab




% MATLAB code for swapping element
% of the array row-wise
% Initializing an array
A = [1 2 3
     4 5 6
     7 8 9];
 
% Calling the randperm() function with
% size() as its parameter
random = A(randperm(size(A, 1)),:)


Output:

random =
  7   8   9
  1   2   3
  4   5   6

Example 2:

Matlab




% MATLAB code for swapping elements
% of the array column-wise
% Initializing an array
A = [1 2 3
     4 5 6
     7 8 9];
 
% Calling the randperm() function with
% size() as its parameter
random = A(:, randperm(size(A, 1)))


Output:

random =
  3   1   2
  6   4   5
  9   7   8


How to swap elements in the matrix in MATLAB?

In this article, we will see the swapping of elements into a matrix in MATLAB. Different methods are illustrated below:

Similar Reads

Method 1: By changing elements of rows and columns

In this method, we are simply changing the elements of particular rows and columns in the specified rows and columns respectively....

Method  2: By using randperm() and size() functions

...