Reputation: 15
Is there a way to vectorize this code piece?
for k=1:K
vec_y(:,k) = y == k;
end
Here, y
is a vector of 3000x1
dimension, and has elements 1
through 10
(representations) such that each representation has equal count as every other representation (i.e., there will be 300
counts of 1
, 300
counts of 2
, etc.).
What I want to do is rewrite or just create a new matrix that has the following binary representation for all occurrences of corresponding 1
-10
:
1
will be represented by [1;0;0;0;0;0;0;0;0;0]
, 2
will be [0;1;0;0;0;0;0;0;0;0]
, and so on.
I want to fully vectorize the code without using for
loop.
Upvotes: 0
Views: 58
Reputation: 4549
EDIT: as suggested by @Suever
One possibility:
% Sample y values
y = [1;9;5;6;3]
% Resulting matrix
m = bsxfun(@eq, 1:10, y)
m =
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 0 0
Upvotes: 3