第一个矩阵表1包含标准化值。我需要对此矩阵执行一些操作,我必须获得第二个矩阵,如表2所示。
table2的对角元素应该通过给每个值赋予秩(序数值)来获得。这意味着最高元素被赋予第5等级,接下来第4等等第3等等。
通过给从4开始的每个值赋予等级而得到的表的剩余元素,因为只剩下4个元素。因为我们已经给对角元素赋予了等级。零应该保持原样。假设将table1作为矩阵,table2作为B矩阵。
OPERATION1:For diagonal elements
B(1,1)=5(first largest element)
B(2,2)=1(5th largest element)
B(3,3)=4(4th largest element)
B(4,4)=2(2nd largest element)
B(5,5)=3(3rd largest element)
OPERATION2:For remaining elements
B(1,2)=3(2nd largest element)
B(1,3)=4(1st largest element)
B(1,4)=1(4th largest element)
B(1,5)=2(3rd largest element)
等等..
Table1:
1.0000 0.2727 0.3182 0.0455 0.2727
0.2727 0.2727 0 0 0
0.3182 0 0.4545 0.1818 0
0.0455 0 0.1818 0.2727 0.0909
0.2727 0 0 0.0909 0.3636
Source code:
for i = 1:5
for j = 1:5
if i == j
[~, ii] = sort(diag(y));
[~, jj] = sort(ii);
table2 = diag(jj);
elseif y(i,j)==0
table2(i,j)=0;
else
[~, ij] = sort(y);
[~, ij] = sort(ij);
table2 = ij;
end
end
end
I got this output for above code
5 0 0 0 0
0 1 0 0 0
0 0 4 0 0
0 0 0 2 0
0 0 0 0 3
但我需要低于输出。表2:
5 3 4 1 2
4 1 0 0 0
4 0 4 3 0
2 0 4 2 3
4 0 0 3 3
答案 0 :(得分:1)
这是一个解决方案(没有任何循环):
E = logical(eye(size(table1))); % create a mask for the two different rules
% rule 1: diagonal elements first
table2 = zeros(size(table1)); % create result matrix
[~,jj] = sort(table1(E));
[~,ii] = sort(jj);
table2(E) = ii; % assign rank of diagonal elements
% rule 2: rest of the matrix
E = ~E;
B = reshape(table1(E),size(table1,1)-1,size(table1,2))'; % B is the matrix of table1 without diagonal elements
[~,jj] = sort(B,2); % sort along column dimension,
[~,ii] = sort(jj,2);
table2 = table2'; % matlab is column-major, so you have to transpose the dest matrix before putting in the elements
table2(E) = reshape(ii',[],1);
table2 = table2'; % transpose back, done.
% treat zeros apart: 0 has rank 0
table2(table1==0) = 0;
某些元素可能与您的预期不同:它们共享相同的值;所以他们的排名是相当随意选择的。 Matlab具有稳定的排序,因此第一个元素的排名高于后面具有相同值的元素。