我想将索引向量转换为矩阵,其中索引所在的列中有1。
x = [2;1;3;1];
m = someFunc(x,3)
% m =
%
% 0 1 0
% 1 0 0
% 0 0 1
% 1 0 0
x = [2;1;3;1];
m = someFunc(x,3)
% m =
%
% 0 1 0
% 1 0 0
% 0 0 1
% 1 0 0
我测试了sub2ind函数,但在coursera机器学习论坛上,有人向我推荐了这个神器。
m = eye(num_cols)(x,:);
它使用恒等矩阵根据x中的值选择适当的列。
eye(4)(3,:)
,这将获取单位矩阵的第三行。然后尝试使用向量eye(4)([2,3,1], :)
。这将获取单位矩阵的第二、第三和第一行。 - Hans Then一种方法是使用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;
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)
accumarray
,这使得这个过程非常简单,像这样:accumarray([ (1:length(x))', x ], 1, [4, 3])
1:length(x)
部分指定了 1 的位置所在的行,x
指定了它们所在的列。