How to create a symmetrical matrix?
157 次查看(过去 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!