Swapping Two Elements in Each Row of a Matrix Without Loop in MATLAB
Last Updated :
15 Mar, 2022
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
flag=logical([0 0 1 1]);
p=perms(flag);
index1=randi(24,5,1);
index=p(index1,:);
A=reshape(1:20,5,4)
B=A';
data=B(index');
data=reshape(data,2,[])
data=data([2,1],:)
B(index')=data;
B=B'
|
Output:
Share your thoughts in the comments
Please Login to comment...