Generate boolean matrix by predicate on row and column

matlab, matrix, octave

Solution

You can try this if `a` is a column vector

a =  [1; 3; 2; 3; 1];

bsxfun(@eq, a, [1:max(a)]) 

and this if it is a row vector

a =  [1; 3; 2; 3; 1]';

bsxfun(@eq, a', [1:max(a)]) 

Problem

I have the following vector: ``` y = [1; 3; 2; 3; 1]; ``` All its values are between `1` and `n` (in this case, `3`) and denote different options. I want to create a matrix of size `size(y, 1)` x `n` whose rows correpond to `y` values: ``` 1 0 0 % because y(1) = 1 0 0 1 % because y(2) = 3 0 1 0 % because y(3) = 2 0 0 1 1 0 0 ``` One way to do this would be ``` Y = zeros(size(y, 1), num_labels); for i = 1:m Y(i, y(i)) = 1; end ``` Is there a better way to do this, maybe in a single expression? Basically, what I need is to generate a matrix with boolean predicate `(i, j) => j == y(i)`.

Original source

Related problems