bachr
bachr

Reputation: 6006

octave use vector as columns index for a matrix

I've a vector y = [1; 1; 2; 3] and a matrix Y = zeros(4, 3). I need to set to 1 the columns in Y that corresponds to values of the vector y. i.e.

Y = [1, 0, 0; 1, 0, 0; 0, 1, 0; 0, 0, 1]

Y(y) or Y(:, y) does not give me the result I need!

Any idea how I could achieve this?

Upvotes: 0

Views: 174

Answers (1)

carandraug
carandraug

Reputation: 13081

You need to convert those columns indices into linear indices. You do it like so:

octave:1> A = zeros (4, 3);
octave:2> c_sub = [1, 1, 2, 3];
octave:3> ind = sub2ind (size (A), 1:rows(A), c_sub)
ind =

    1    2    7   12
octave:4> A(ind) = 1
A =

   1   0   0
   1   0   0
   0   1   0
   0   0   1

However, if your matrix is that sparse, do create a proper sparse matrix:

octave:4> sparse (1:4, c_sub, 1, 4, 3)
ans =

Compressed Column Sparse (rows = 4, cols = 3, nnz = 4 [33%])

  (1, 1) ->  1
  (2, 1) ->  1
  (3, 2) ->  1
  (4, 3) ->  1

and maybe consider using a logical matrix (use false instead of zeros and true instead of 1.

Upvotes: 2

Related Questions