我想将索引向量转换为索引列中的索引的矩阵.
x = [2;1;3;1];
m = someFunc(x,3)
% m =
%
% 0 1 0
% 1 0 0
% 0 0 1
% 1 0 0
Run Code Online (Sandbox Code Playgroud)
Han*_*hen 15
我测试了sub2ind功能,但是在机器学习论坛上我指出了这个美.
m = eye(num_cols)(x,:);
Run Code Online (Sandbox Code Playgroud)
它使用单位矩阵根据x中的值选择适当的列.
一种方法是使用 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;
Run Code Online (Sandbox Code Playgroud)