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.

Example 1:

Matlab




% MATLAB code for 2*2 matrix. its first and
% second elements of the first column are being swapped
A = [5  10
     15 20]
      
% Swapping the first and second elements of the first column
A([1 2]) = A([2 1])


Output:

A =
   5   10
  15   20
A =
  15   10
   5   20

Example 2:

Matlab




% MATLAB code for 3*3 matrix. The second and third elements of the first
% column are being swapped. And later, the first and second elements
% of the second column of the swapped matrix are swapped again.
A = [5  10 15
     20 25 30
     35 40 45]
      
% Swapping the second and third elements of the first column
A([2 3]) = A([3 2])
 
% Swapping the first and second elements of the second column
% of the above swapped matrix
A([4 5]) = A([5 4])


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

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

...