adn*_*adn 5 sorting indexing matlab matrix
假设您有一个1D矩阵
a = rand(1,5);
[sa i] = sort(a);
Run Code Online (Sandbox Code Playgroud)
然后sa和a(i)相同。但是,如果矩阵的大小增加
a = rand(3,4);
[sa i] = sort(a);
Run Code Online (Sandbox Code Playgroud)
然后sa和a(i)不一样。当我尝试按3D矩阵对3D矩阵进行排序时,也会发生同样的情况。
如何a通过索引访问的值i?或者换句话说,我该如何计算sa=a(X),X应该是什么?
编辑:
感谢您的解决方案。但是,当您更改维度以进行排序时,它们不起作用。尽管如此,我还是接受了这个想法并用它来构建一个通用的表单。
该算法正在做的是建立矩阵的索引。MATLAB会按列对单元格进行索引。因此,索引由
idx = r + (c-1)*ROWS + (p-1)*ROWS*COLS
Run Code Online (Sandbox Code Playgroud)
其中,idx是索引,r是行位置,c是列位置,p是页面位置。
因此,如果我们按第一个维度(normal sort(a))进行排序,则结果索引是列中的位置;如果我们在第二维中排序,则结果索引是行中的位置;如果我们按三维排序,则结果索引是页面位置。话虽如此,它只会最后产生给定情况的行和列:
r = repmat((1:rows)',[1 cols pages]);
c = repmat(1:cols,[rows 1 pages]);
Run Code Online (Sandbox Code Playgroud)
在给定的解决方案中说明了对第一维的排序。然后,让我们对二维数组的第二维(行)进行排序
a = rand(4,5);
[rows cols pages] = size(a);
R = repmat((1:rows)',[1 cols pages]);
[sa idx] = sort(a,2);
nIdx = R + (idx-1)*rows;
isequal(sa,a(nIdx))
Run Code Online (Sandbox Code Playgroud)
现在,如果我们对第三维进行排序时使用相同的想法(逐页),我们需要
a = rand(4,5,3);
[rows cols pages] = size(a);
R = repmat((1:rows)',[1 cols pages]);
C = repmat(1:cols,[rows 1 pages]);
[sa idx] = sort(a,3);
nIdx = R + (C-1)*rows + (idx-1)*rows*cols;
isequal(sa,a(nIdx))
Run Code Online (Sandbox Code Playgroud)
并且可以使用相同的逻辑将其扩展到N个维度。感谢您的帮助,为您提供了方便。:)
[sa, i]=sort(a)返回每列的有序索引。您只需要获得矩阵的正确线性索引即可。因此,对于二维矩阵,
A=rand(3,4);
[rows,cols]=size(A);
[B,index]=sort(A,1);
correctedIndex=index+repmat(0:cols-1,rows,1)*rows;
Run Code Online (Sandbox Code Playgroud)
现在测试一下:
A =
0.9572 0.1419 0.7922 0.0357
0.4854 0.4218 0.9595 0.8491
0.8003 0.9157 0.6557 0.9340
B =
0.4854 0.1419 0.6557 0.0357
0.8003 0.4218 0.7922 0.8491
0.9572 0.9157 0.9595 0.9340
A(correctedIndex)
ans =
0.4854 0.1419 0.6557 0.0357
0.8003 0.4218 0.7922 0.8491
0.9572 0.9157 0.9595 0.9340
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5255 次 |
| 最近记录: |