Reputation: 1370
In Octave, I have a vector with indexes e.g. a = [ 1 2 3 1 2 3]
. I now want a matrix m = zeros(size(a,2), max(a))
to have ones depending on vector a:
m =
[1 0 0
0 1 0
0 0 1
1 0 0
0 1 0
0 0 1]
How do I do that?
I tried this, but it didn't work: m(a,:) = 1;
Upvotes: 0
Views: 66
Reputation: 159
You can also index into an identity matrix like so.
a = [ 1 2 3 1 2 3];
I = eye(max(a));
m = I(a, :);
Upvotes: 0
Reputation: 45752
Assuming:
a = [1 2 3 1 2 3];
sz = [numel(a), max(a)];
using sub2ind
:
m = zeros(sz);
ind = sub2ind(sz, 1:sz(1), a);
m(ind) = 1;
using sparse
m = full(sparse(1:sz(1), a, 1));
Upvotes: 3