Swapping Two Elements in Each Row of a Matrix Without Loop in MATLAB
Last Updated :
15 Mar, 2022
Improve
A Matrix is a two-layered cluster of numbers. In MATLAB, we can create a Matrix by entering components in each line as comma or space-delimited numbers and also, utilizing semicolons to stamp the finish of each line.
Approach:
- Step 1: Pick 2 elements in a row using logical()
- Step 2: Get all possible Combinations using perms()
- Step 3: Pick 5 Random Numbers from 1 to 24 using Randi() function
- Step 4: Logical Index to Pick Numbers in Each Row
- Step 5: Create A Matrix (Original)
- Step 6: Transpose the Matrix
- Step 7: Pick the Data. Each column contains two numbers from each row in the matrix A
- Step 8: Swap the values
- Step 9: Fill Back the Data
- Step 10: Transpose to give the Final Result
Example:
% MATLAB Program to Swap 2 Elements
% in each row without Loops
% Step1 : Pick 2 elements in a row
flag=logical([0 0 1 1]);
% Step2 : Get all possible Combinations
p=perms(flag);
% Step3 : Pick 5 Random Numbers from 1 to 24
index1=randi(24,5,1);
% Step4 : Logical Index to Pick Numbers in Each Row
index=p(index1,:);
% Step5 : Create A Matrix (Original)
A=reshape(1:20,5,4)
% Step6 : Transpose the Matrix
B=A';
data=B(index');
% Step7 : Pick the Data
% Each column contains two numbers from each row in the matrix A
data=reshape(data,2,[])
% Step8 : Swap the values
data=data([2,1],:)
% Step9 : Fill Back the Data
B(index')=data;
% Step10 : Transpose to give the Final Result
B=B'
Output: