How to switch an element in matrix at for example (4,10) to be at (10,4)
2 views (last 30 days)
Show older comments
Hi
How can i equate an element in a matrix at (x,y) location to a new position at (y,z). I want to interchange the column and row of the element. It will be nice to have it in a for loop
0 Comments
Answers (2)
Walter Roberson
on 1 Feb 2019
YourMatrix([row1 row2], :) = YourMatrix([row2 row1], :);
exchanges row1 and row2 .
YourMatrix(:, [col1 col2]) = YourMatrix(:, [col2 col1]);
exchange column col1 and column col2.
0 Comments
Star Strider
on 1 Feb 2019
Try this:
M = randi(9, 4, 5) % Create Matrix
R = 2; % Original Row
C = 4; % Original Column
T = M(R,C); % Store Value
M(R,C) = M(C,R); % Switch
M(C,R) = T % Output With Switched Elements
Create a loop to do that if you want to switch more elements.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!