Diagonal/Symmetric matrix

조회 수: 5 (최근 30일)
Kimhim Chhay
Kimhim Chhay 2019년 11월 9일
댓글: John D'Errico 2019년 11월 9일
Hi, I'm new to matlab. I wanted to make a program that takes a nxn matrix and outputs a symetric matrix such that the elements are the average of the 2 diagonals elements of the original matrix. I suceeded with a 3x3, but it won't work for a nxn. Here's my code so far.
clear
clc
PA = [81 3 15;
43 67 90;
22.5 10 68]
for i=1:length(PA)
OD(i,i) = PA(i,i);
end
for i=2:length(PA)
OD(1,i) = (PA(1,i) + PA(i,1))/2;
OD(i,1) = OD(1,i);
end
OD(2,end) = (PA(end,2)+PA(2,end)) / 2;
OD(end,2) = OD(2,end)

채택된 답변

John D'Errico
John D'Errico 2019년 11월 9일
I don't even think your code works for a 3x3 matrix. The matrix it produces is
OD
OD =
81 23 18.75
23 67 50
18.75 0 68
Give the matrix PA, note that the (3,2) element does not seem to be correct, at least by my guess as to what you really want to do.
However, I think what you may be asking is how to do the following computation:
OD = (PA + PA.')/2
OD =
81 23 18.75
23 67 50
18.75 50 68
I'm not sure why you would want to write a complicated routine using loops to do exactly that. Note that what I wrote will work for any square matrix. And it took one line of code.
  댓글 수: 2
Kimhim Chhay
Kimhim Chhay 2019년 11월 9일
Thank you. I didn't even realize I was adding the transpose.
John D'Errico
John D'Errico 2019년 11월 9일
This is the standard way in MATLAB to symmetrize a matrix, having learned it on the order of 30 years ago.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by