Attempting to rearrange a 3x3 "magic" matrix
9 views (last 30 days)
Show older comments
[EDIT: Sat Jun 25 00:40:09 UTC 2011 - Reformat - MKF]
Hello, here is the code that I am currently attempting to get to take the given matrix and move the rows up 1 to get the top row on the bottom and each row moved up one spot, so the 2nd row is on the top, and the last row is now in the middle. When I attempt to use the code provided for example 2.3, I get the top row and the last row to swap, but of course that is not what the question is asking, what am I doing wrong? I can fix the problem, but I will have to not follow the directions to get it done. Thanks...
clc
clear
matr = magic(3)
Temp1 = matr(1,:);
matr(1,:) = matr(3,:);
matr(3,:) = Temp1;
Temp1 = matr(2,:);
matr
0 Comments
Accepted Answer
bym
on 25 Jun 2011
try
doc circshift
3 Comments
Paulo Silva
on 25 Jun 2011
it's just one simple line of code and there's no need to use additional memory.
More Answers (2)
Paulo Silva
on 25 Jun 2011
m=magic(3);
m=[m(2:end,:);m(1,:)]; %works for any magic array size
7 Comments
Paulo Silva
on 25 Jun 2011
The code I provided in my first answer works the way you need, you can also use the circshift like this m=circshift(m,-1); and get the same results.
Matt Fig
on 25 Jun 2011
If it must be done using storage techniques (as you seem to be suggesting), simply work your way down the matrix.
M = magic(3);
TMP = M(1,:);
M(1,:) = M(2,:);
M(2,:) = TMP;
TMP = M(2,:);
M(2,:) = M(3,:);
M(3,:) = TMP
Or, for a more general approach:
for ii = 1:size(M,1)-1
TMP = M(ii,:);
M(ii,:) = M(ii+1,:);
M(ii+1,:) = TMP;
end
Of course it goes without saying that this is not really the way to do it in MATLAB. Much preferred is (for one):
M = M([2:size(M,1), 1],:)
See Also
Categories
Find more on R Language 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!