Create dummy variables from elements of a cell

1 ビュー (過去 30 日間)
Maria
Maria 2014 年 8 月 14 日
回答済み: Azzi Abdelmalek 2014 年 8 月 14 日
I have a cell type variable X with 100 rows and 8 columns. Here is an example:
X={
c1 c2 c3 c4 c5 c6 c7 c8
18 1 53.33 15.08 67 16 20601 1999
26 0 53.96 14.20 11 254 40406 1998
29 0 60.54 2.38 13 100 20601 1997
44 0 51.25 16.06 115 254 20601 1999 }
From c4 (included)and onwards I am trying to create dummy variables for each single different value. For instance, in this example in c8 I would only create 3 dummy variables (1997, 1998, 1999). But in c5 I will have to create 4 different dummies (67, 11,13,115). So in this example what I would have would be something similar to this:
c1 c2 c3 15.08 14.20 2.38 16.06 67 11 13 115 16 254 100 20601 40406 1999 1998 1997
18 1 53.33 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0
26 0 53.96 0 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0
29 0 60.54 0 0 1 0 0 0 1 0 0 0 1 1 0 0 0 1
44 0 51.25 0 0 0 1 0 0 0 0 0 1 0 1 0 1 0 0
Can someone help me? Thank you.

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 8 月 14 日
X={'c1' 'c2' 'c3' 'c4' 'c5' 'c6' 'c7' 'c8'
18 1 53.33 15.08 67 16 20601 1999
26 0 53.96 14.20 11 254 40406 1998
29 0 60.54 2.38 13 100 20601 1997
44 0 51.25 16.06 115 254 20601 1999 }
a=unique(cell2mat(X(2:end,4:end)),'stable');
v(1,1:3)=X(1,1:3);
v(3+1:3+numel(a))=num2cell(a);
for k=2:size(X,1)
idx{k-1}=ismember(cell2mat(v(1,4:end)),cell2mat(X(k,4:end) ));
end
out=[v;[X(2:end,1:3) num2cell(cell2mat(idx'))]]

その他の回答 (0 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by