我想将索引向量转换为索引列中的索引向量。将索引向量转换为矩阵
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功能:
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)
我测试了sub2ind函数,但在coursera机器学习论坛上,我被指出了这个美。
m = eye(num_cols)(x,:);
它使用单位矩阵来选择基于在x中的值相应的列。
您可以使用accumarray
这使得这个非常容易,就像这样:
accumarray([ (1:length(x))', x ], 1, [4, 3])
的1:length(x)
部分指定入行的人去了,x
入列。
可能重复[如何更改矩阵中多个点的值?](http://stackoverflow.com/questions/6850368/how-can-i-change-the-values-of-multiple-指向功能于一个矩阵) – gnovice 2012-03-30 17:26:49