我有一个标签向量如下:
y=[3 1 5 3 4 2];是否有任何有效的方法来生成以下标签矩阵?
[0 0 1 0 0;
1 0 0 0 0;
0 0 0 0 1;
0 0 1 0 0;
0 0 0 1 0;
0 1 0 0 0;]更新: This post和this post都是很好的答案。使用@Nras提供的脚本,可以处理缺少的标签:
Y=[3 1 5 3 4 2];
labels=unique(Y);
[~,indexes]=ismember(Y,labels);
rows = 1:length(Y); %// row indx
T = zeros(length(Y),length(unique(indexes))); %// A matrix full of zeros
T(sub2ind(size(T),rows ,indexes)) = 1; %// Ones at the desired row/column combinations发布于 2014-12-08 08:35:31
对于此问题,请使用sub2ind。您的y确定要使用的列,行总是增加1。通过使用sub2ind,所需的行列组合被转换为线性索引,然后所有行都可以以向量化的方式嵌入。
y = [3 1 5 3 4 2]; %// column indx
rows = 1:length(y); %// row indx
M = zeros(length(y), max(y)); %// A matrix full of zeros
M(sub2ind(size(M),rows ,y)) = 1; %// Ones at the desired row/column combinationshttps://stackoverflow.com/questions/27354044
复制相似问题