Gnubie
Gnubie

Reputation: 2607

How to convert a vector into a matrix where values on columns are 1 where the column number is the vector element, else 0?

I'm unsure how to phrase the question, but I think an example will help. Suppose I have a vector y = [3;1;4;1;6]. I want to create the matrix Y =

[0     0     1     0     0     0;
 1     0     0     0     0     0;
 0     0     0     1     0     0;
 1     0     0     0     0     0;
 0     0     0     0     0     1]

 ↑     ↑     ↑     ↑     ↑     ↑
 1     2     3     4     5     6

where the element on each column is one or zero corresponding to the value in the vector.

I found that I could do it using

Y = []; for k = 1:max(y); Y = [Y (y==k)]; end

Can I do it without a for loop (and is this method more efficient if y has thousands of elements)?

Thanks!

Upvotes: 3

Views: 103

Answers (4)

Gnubie
Gnubie

Reputation: 2607

Another solution:

Y = repmat(1:max(y), size(y)) == repmat(y, 1, max(y))

Upvotes: 0

Sardar Usama
Sardar Usama

Reputation: 19689

Your method is not efficient because you're growing the size of Y in the loop which is not a good programming practice. Here is how your code can be fixed:

Ele = numel(y); 
Y= zeros(Ele, max(y));
for k = 1:Ele
    Y (k,y(k))= 1;
end

And here is an alternative approach without a loop:

Ele = numel(y);          %Finding no. of elements in y
Y= zeros(Ele, max(y));   % Initiailizing the matrix of the required size with all zeros
lin_idx = sub2ind(size(Y), 1:Ele, y.'); % Finding linear indexes
Y(lin_idx)=1             % Storing 1 in those indexes

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112659

You can use bsxfun:

result = double(bsxfun(@eq, y(:), 1:max(y)));

If you are running the code on Matlab version R2016b or later, you can simplify the syntax to

result = double(y(:)==(1:max(y)));

Another approach, possibly more efficient, is to fill in the values directly using accumarray:

result = accumarray([(1:numel(y)).' y(:)], 1);

Upvotes: 2

Gnubie
Gnubie

Reputation: 2607

I found another solution:

E = eye(max(y));
Y = E(y,:);

Upvotes: 1

Related Questions