0

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;

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
user1406177
  • 1,328
  • 2
  • 22
  • 36
  • in your specific case you can do `[eye(3); eye(3)]` – Dan Jan 07 '15 at 13:56
  • That's true, but a could also be `a = [1 1 3 2 1 3]` – user1406177 Jan 07 '15 at 13:59
  • 1
    possible duplicate of [Creating an m by n matrix of 0s and 1s from m-sized vector of column indexes](http://stackoverflow.com/questions/10665179/creating-an-m-by-n-matrix-of-0s-and-1s-from-m-sized-vector-of-column-indexes) – Stewie Griffin Jan 07 '15 at 16:22

2 Answers2

3

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));
Dan
  • 45,079
  • 17
  • 88
  • 157
  • 1
    Nice answer. IMO, the following is a bit simpler `full(sparse(1:numel(a), a, 1))`. – Stewie Griffin Jan 07 '15 at 16:20
  • @user1406177 Look at the last answer to this duplicate question: http://stackoverflow.com/questions/10665179/creating-an-m-by-n-matrix-of-0s-and-1s-from-m-sized-vector-of-column-indexes it makes use of broadcasting in Octave whih Matlab doesn't have and is much simpler. However, I would recommend against using this method as you will remove compatibility with Matlab which, even if it seems irrelevant to you now, is probably something worth preserving as it makes you code portable. – Dan Jan 08 '15 at 06:04
0

You can also index into an identity matrix like so.

a = [ 1 2 3 1 2 3];

I = eye(max(a));
m = I(a, :);
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
simlist
  • 159
  • 2
  • 4