How to create a symmetrical matrix?
154 ビュー (過去 30 日間)
古いコメントを表示
Hi, I have to fill a matrix with some data that come from a subroutine. The matrix is symmetrical over the two diagonals, so I have to build just a quarter of it and then to copy one the other parts. How can I do?
1 件のコメント
採用された回答
Stephen23
2017 年 2 月 3 日
編集済み: Stephen23
2017 年 2 月 3 日
I looked at this task, and tried several possibilities to convert this:
>> M = [1,2,3,4,5;0,6,7,8,0;0,0,9,0,0;0,0,0,0,0;0,0,0,0,0]
M =
1 2 3 4 5
0 6 7 8 0
0 0 9 0 0
0 0 0 0 0
0 0 0 0 0
But then it occurred to me: the question states "I have to fill a matrix with some data that come from a subroutine", so perhaps the simplest way is to avoid it all together: if you have to fill the matrix with these values (presumably in a loop and using some indexing), then instead of just filling one value, fill in all four values at once. This is likely going to be simpler than any method of taking that quarter matrix, rotating, and merging again...
So the simplest way for your situation might be to not "copy and rotate", but to allocate each new value to four locations when you put it into the matrix:
S = size(M);
[R,C] = find(M);
Z = nan(S);
for k = 1:numel(R) % for each subroutine value
x = [R(k),1+S(1)-R(k),C(k),1+S(2)-C(k)]; % index
m = M(R(k),C(k)); % new subroutine value here
Z(x,x) = m;
end
which gives this:
Z =
5 4 3 4 5
4 8 7 8 4
3 7 9 7 3
4 8 7 8 4
5 4 3 4 5
Or you can use the method exactly as I did here: to copy the elements of that quarter to the other quarters.
0 件のコメント
その他の回答 (2 件)
Benjamin Klassen
2023 年 1 月 26 日
Symmetric Matrix Generator
% Rows
r1=[1,2,3,4,5,6,7,8];
r2=[5,2,6,7,9,8,5];
r3=[1,4,6,2,8,6];
r4=[1,6,2,9,4];
r5=[1,3,2,7];
r6=[1,7,9];
r7=[6,2];
r8=[9];
nr=length(r1); % Number of rows
K=zeros(nr,nr);
% Symmetric Matrix Assembly
for i=1:nr
d=join(['r',num2str(i)])
rowvalues=eval(d);
K(i,i:end)=rowvalues;
K(i:end,i)=rowvalues;
end
参考
カテゴリ
Help Center および File Exchange で Operating on Diagonal Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!