给定一个二进制矩阵,其中每行和每列都只包含一个 1,我需要按列重新排列矩阵,使其成为单位矩阵。例如,给定一个二进制矩阵:
Binary = [ 0 1 0 0 0
0 0 1 0 0
1 0 0 0 0
0 0 0 0 1
0 0 0 1 0 ]
为了获得单位矩阵,我们将列重新排列为 2 3 1 5 4
。
我们如何才能以最佳方式重新排列任意给定的任意二进制二元矩阵的列?
最佳答案
执行此操作的一个非常简单的方法是使用函数 FIND像这样:
[index,~] = find(Binary.'); %'# Transpose the matrix and find the row indices
%# of the non-zero entries
您可以按如下方式测试它是否工作:
>> Binary(:,index)
ans =
1 0 0 0 0 %# Yup, that's an identity matrix alright!
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
旧方法:
这不像上面的解决方案那么紧凑或高效,但您也可以转置矩阵并使用 SORTROWS对列进行排序(现在转置为行)并返回排序索引。这实际上会按升序对值进行排序,这将为您提供一个反对角矩阵,因此您需要使用 FLIPUD 翻转索引向量。 。代码如下:
[~,index] = sortrows(Binary.'); %'# Transpose and sort the matrix
index = flipud(index); %# Flip the index vector
关于matlab - 如何重新排列该矩阵的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6203827/