2014-12-08 86 views
0

我有一个标签矢量如下:如何从标签矢量生成标签矩阵?

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 postthis 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 
+0

也重复的:http://stackoverflow.com/questions/6150174/creating-indicator-matrix – Shai 2014-12-08 12:06:01

+1

次要注:重复适用于生成矩阵,其中列** **表示的非零值。只需转换结果即可获得您问题中所见的行矩阵。顺便说一句,感谢链接到我的答案@Shai :) – rayryeng 2014-12-08 16:59:10

+1

@rayryeng有相当多的几个线程,这里几乎是相同的(我甚至认为我已经回答其中之一...),但恕我直言,这个问题是最“经典”。 – Shai 2014-12-08 17:38:42

回答

1

使用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 combinations 
+0

就是这样!谢谢! – mining 2014-12-08 08:43:11

+0

但我建议你可以在你的答案中加入'unique'函数,因为'y'向量可能没有标签'2'或其他值。 – mining 2014-12-08 08:44:54

+0

好答案+1。 – Rashid 2014-12-08 08:50:06