在matlab中按升序排列矩阵值

时间:2014-05-08 05:27:40

标签: matlab sorting matrix

对于给定的矩阵R = {r(i,j)}以下是为输入矩阵完成的3个操作:

1.我们按升序排列对角线值(即给出小值等级1和下一个小值等级2等等)

2.对于零小区,给出了等级1。

3.除了对角线单元格和零单元格之外,我们按升序对休息值进行排序。(零单元格数将设置为初始排名顺序,即零单元格排名第一)

主要示例

这是我的输入矩阵。

0.6667    0.1667    0.1667         0    0.6667
0.1667    0.1667    0.1667         0    0.1667
0.1667    0.1667    0.1667         0    0.1667
     0         0         0         0         0
0.6667    0.1667    0.1667         0    1.0000

预期的输出矩阵是:

 4     2     3     1     4
 4     3     3     1     2
 4     3     2     1     2
 1     1     1     1     1
 4     3     2     1     5

但是我为我的代码得到了这个输出矩阵:

 4     1     4     0     2
 3     2     4     0     1
 3     4     3     0     1
 0     0     0     0     0
 4     3     2     0     5

我试过的源代码:

%to display ordinal graph
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;
            disp(table2);

示例1

输入矩阵:

  12  6  6  4  12

  6   6  6  4   6

  6   6  6  4   6

  4   4  4  4   4

  12  6  6  4  16

预期输出矩阵:

 4  3  2  1  4
 4  3  2  1  3
 4  3  2  1  2
 4  3  2  1  1
 4  3  2  1  5

示例2

输入矩阵:

 10   11  0  13  14
 14    9  8  20   7
 20   25  22 18  13
 16    8  9  23  19
 15    0  0  16  21

预期输出矩阵:

 2  2  1  3  4
 3  1  2  4  1
 3  4  4  2  1
 3  1  2  5  4
 2  1  1  3  3

1 个答案:

答案 0 :(得分:1)

在处理排序相同值时,问题中的索引似乎存在问题,但假设这不会影响最终结果,您可以尝试使用5x5矩阵 -

%%// A is your input matrix

%%// Pre-allocate output matrix
out = zeros(size(A));

%%// Take care of operation #3
for k = 1:5
    [~,ind2] = sort(A(k,:))
    ind2(ind2)=1:5;
    out(k,:) = ind2;
end
out = out-bsxfun(@gt,out,diag(out))

%%// Take care of assigning diagonal elements
[~,ind1] = sort(diag(A))
ind1(ind1)=1:5
out(1:size(out,1)+1:end)=ind1