将指数矢量转换为矩阵

时间:2012-03-30 17:10:49

标签: matlab

我想将索引向量转换为索引列中包含1的矩阵。

x = [2;1;3;1];
m = someFunc(x,3)
% m =
%
%   0   1   0
%   1   0   0
%   0   0   1
%   1   0   0

4 个答案:

答案 0 :(得分:15)

我测试了sub2ind功能,但是在机器学习论坛上,我被指向了这个美丽。

m = eye(num_cols)(x,:);

它使用单位矩阵根据x中的值选择适当的列。

答案 1 :(得分:3)

一种方法是使用SUB2IND功能:

colN = 3;
assert(max(x)<=colN,'Not enough columns') %# check that you have enough columns
%# other checks that x is valid indices

m = zeros(numel(x),colN);
m(sub2ind(size(m),1:numel(x),x')) = 1;

答案 2 :(得分:1)

我有一个非常相似的问题,所以我不想开一个新问题。我想将索引的行向量转换为矩阵,其中索引的行(而不是列)中有一个。我可以使用之前的答案并将其反转,但我认为这对于非常大的矩阵会表现得更好。

octave> x = [2 1 3 1];
octave> m = setRowsToOne(x, 3)
m =

   0   1   0   1
   1   0   0   0
   0   0   1   0

我无法看到如何使用sub2ind来完成此任务,所以我自己计算了。

function matrixResult = setRowsToOne(indexOfRows, minimumNumberOfRows)
   numRows = max([indexOfRows minimumNumberOfRows]);
   numCols = columns(indexOfRows);
   matrixResult = zeros(numRows, numCols);
   assert(indexOfRows > 0, 'Indices must be positive.');
   matrixResult(([0:numCols-1]) * numRows + indexOfRows) = 1;
end

x = [2 1 3 1];
m = setRowsToOne(x, 3)

答案 3 :(得分:0)

您可以使用accumarray这样做非常简单,如下所示:

accumarray([ (1:length(x))', x ], 1, [4, 3])

1:length(x)部分指定了哪些行以及x列到哪些列。

相关问题