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)
.
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)])
If you have access to Statistics Toolbox, the command dummyvar
does exactly what you need.
>> y = [1; 3; 2; 3; 1];
>> dummyvar(y)
ans =
1 0 0
0 0 1
0 1 0
0 0 1
1 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With