0

I've a label vector as follows:

 y=[3 1 5 3 4 2]; 

Is there any efficient way to generate the following label matrix?

 [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;] 

UPDATED: This post and this post are both good answers. Using the scripts provided by @Nras, the following is to handle the missing labels:

 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 
4
  • also duplicate of: stackoverflow.com/questions/6150174/creating-indicator-matrix Commented Dec 8, 2014 at 12:06
  • 1
    Minor note: The duplicate applies for generating matrices where the columns denote the non-zero values. Simply transpose the result to get a row matrix as seen in your question. BTW, thanks for linking to my answer @Shai :) Commented Dec 8, 2014 at 16:59
  • 1
    @rayryeng there are quite a few threads that are practically the same here (I even think I have answered one of them...), but IMHO this question is most "canonical". Commented Dec 8, 2014 at 17:38
  • 1
    @Shai, thank you! The post you provided indeed is very good solution. Because when I made this post, I didn't checked your post, thus I made this duplicate post. And I've closed this post. Maybe the stackoverflow could improve the natural language processing techniques to offer the most preferable suggestions when we write down the title of the post. Commented Dec 9, 2014 at 0:12

1 Answer 1

1

Use sub2ind for this problem. Your y determines the columns to use, the rows are simply always incremented by 1. By using sub2ind the desired row-column-combinations get transformed to a linear index and can then all be adressed in a vectorized way.

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 
Sign up to request clarification or add additional context in comments.

3 Comments

But I suggest you could add the unique function into your answer because the y vector may not have the label 2 or other values.
@hubberwinston - The duplicate answer can handle cases where labels are missing.
@rayryeng, thank you for indicating that. The post you provided is very good solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.