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