Swapping a range of points in a matrix
Show older comments
I'm trying to swap rows 6 to 10 in column 1 and rows 1 to 5 in column 2 of my matrix for a task in my computing class. So far this is the best I can manage but something is going wrong, presumably with the square brackets:
r1=zeros(5,6)
r1(2:2:30,1)=1:1:15
r1([1:5,6:10],[2,1])=r1([6:10,1:5],[1,2])
Any help would be much appreciated
1 Comment
dpb
on 26 Nov 2016
Matlab doesn't treat arrays of indices as you're trying to use them; see what the expression returns to understand what you're getting (might want to do it for a smaller range first to get fewer values to look at and clarify what's happening).
To do multiple locations like this you'd need to use linear addressing and compute that location from subscripts via the ind2sub|sub2ind pair or write the column indices a single values in separate expressions.
As it is coursework, will leave as the above hints for further exploration... :)
Answers (2)
Roger Stafford
on 26 Nov 2016
Suppose your matrix is called ‘M’.
T = M(6:10,1);
M(6:10,1) = M(1:5,2);
M(1:5,2) = T;
Roger Stafford
on 29 Nov 2016
If you prefer one-liners, try this, (again calling your matrix M):
M([6:10,(1:5)+size(M,1)]) = M([(1:5)+size(M,1),6:10]);
Categories
Find more on Creating and Concatenating Matrices 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!