我在根据公司编号对一些财务数据进行排序时遇到问题。所以给定的是一个看起来像这样的矩阵:
[1 3 4 7;
1 2 7 8;
2 3 7 8;]
在 Matlab 上,我希望按如下方式对矩阵进行排序:
[1 0 3 4 7 0;
1 2 0 0 7 8;
0 2 3 0 7 8;]
所以基本上每一列都需要包含一种类型的数字。
我已经尝试了很多东西,但我无法正确排序矩阵。
最佳答案
A = [1 3 4 7;
1 2 7 8;
2 3 7 8;]
%// Get a unique list of numbers in the order that you want them to appear as the new columns
U = unique(A(:))'
%'//For each column (of your output, same as columns of U), find which rows have that number. Do this by making A 3D so that bsxfun compares each element with each element
temp1 = bsxfun(@eq,permute(A,[1,3,2]),U)
%// Consolidate this into a boolean matrix with the right dimensions and 1 where you'll have a number in your final answer
temp2 = any(temp1,3)
%// Finally multiply each line with U
bsxfun(@times, temp2, U)
所以你可以在一行中完成所有这些,但我将其分解以使其更容易理解。我建议您运行每一行并查看输出以了解其工作原理。它可能看起来很复杂,但了解 bsxfun
是值得的,因为它是一个非常有用的函数。第一次使用也使用 permute
有点棘手,所以我建议您首先确保您理解最后一行,然后再倒过来。
关于algorithm - Matlab:以独特的方式对矩阵进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24888640/