Change diagonal place

조회 수: 8 (최근 30일)
Paul
Paul 2011년 12월 22일
How can I switch places the diagonal and the first column from a square matrix?
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2011년 12월 23일
You could use an example to explain what you mean.

댓글을 달려면 로그인하십시오.

채택된 답변

bym
bym 2011년 12월 23일
a= magic(3)
a =
8 1 6
3 5 7
4 9 2
>> b=a;
>> for i =2:size(a,1)
b(i,1:i)= fliplr(a(i,1:i));
end
b
b =
8 1 6
5 3 7
2 9 4
  댓글 수: 3
Image Analyst
Image Analyst 2011년 12월 23일
proecsm, I know you know better than that, so I assume you just made a careless error. See my solution for the correct answer. Paul, don't use that method if your size is greater than 3 by 3.
Andrei Bobrov
Andrei Bobrov 2011년 12월 23일
b = 1:size(a,1)+1:numel(a)
c = 1:3
a([b,c]) = a([c,b])

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2011년 12월 23일
This code works of a square matrix of any size. I present both a looping and vectorized way.
a=magic(6)
b=a;
for i =2:size(a,1)
temp = a(i,i);
b(i,i)= b(i,1);
b(i,1) = temp;
end
b
% Loopless way
a=magic(6)
b=a;
diagonalElementsMask = logical(eye(size(a,1)))
% Save diagonal elements, because we're going to replace them.
bDiagonalElements = b(diagonalElementsMask)
% Replace diagonal elements with first column.
b(diagonalElementsMask) = b(:,1);
% Replace first column with diagonal elements.
b(:,1) = bDiagonalElements
a =
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
b =
35 1 6 26 19 24
32 3 7 21 23 25
2 9 31 22 27 20
17 28 33 8 10 15
14 5 34 12 30 16
11 36 29 13 18 4
  댓글 수: 3
Andrei Bobrov
Andrei Bobrov 2011년 12월 23일
b = 1:size(a,1)+1:numel(a)
c = 1:size(a,1)
a([b,c]) = a([c,b])
Image Analyst
Image Analyst 2011년 12월 23일
OK, this one works.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by