2014-12-08 62 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