Efficiently decompress vector into binary Octave matrix

In Octave, I am trying to unpack a vector in the format:

y = [ 1  
      2  
      4  
      1 
      3 ]

      

I want to return a matrix of dimension (rows (y) x max value (y)) where for each row I have 1 in the original digit value column and zero elsewhere, i.e. for example above

y01 = [ 1 0 0 0
        0 1 0 0
        0 0 0 1
        1 0 0 0
        0 0 1 0 ]

      

so far i

y01 = zeros( m, num_labels );
for i = 1:m
    for j = 1:num_labels
        y01(i,j) = (y(i) == j);
    end
end

      

which works, but gets slow for large matrices and seems inefficient because it loops through each individual value, even if most don't change.

I found this for R on another thread :

f3 <- function(vec) {
    U <- sort(unique(vec))
    M <- matrix(0, nrow = length(vec), 
          ncol = length(U), 
          dimnames = list(NULL, U))
    M[cbind(seq_len(length(vec)), match(vec, U))] <- 1L
    M
}

      

but I don't know R and I'm not sure if / how the octave ports solution.

Thanks for any suggestions!

+3


source to share


2 answers


Use a sparse matrix (which also saves a lot of memory), which can be used for further calculations as usual:

y = [1; 2; 4; 1; 3]
y01 = sparse (1:rows (y), y, 1)

      



if you really want a full matrix use "full":

full (y01)
ans =
1   0   0   0
0   1   0   0
0   0   0   1
1   0   0   0
0   0   1   0

      

+5


source


Sparse is a more efficient way to do this when the matrix is ​​large. If your outcome measurement is not very large, you can try this:

y = [1; 2; 4; 1; 3]
I = eye(max(y));
y01 = I(y,:)

      



The result is the same as full (sparse (...)).

y01 =

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

      

+1


source







All Articles