AtomicScience
AtomicScience

Reputation: 169

Julia sparse matrix

I have vector y_vec, How to convert the vector to a matrix of form Y_matrix

y_vec = [0; 1; 1; 2; 3; 4]

Y_matrix = [1 0 0 0 0
            0 1 0 0 0
            0 1 0 0 0
            0 0 1 0 0
            0 0 0 1 0
            0 0 0 0 1]

So far, I've tried using a for loop.

Y_mat = full(spzeros(length(y_vec), length(unique(y_vec))))

for (i,j) in enumerate(1:length(y_vec))
    Y_mat[i, y_vec[j]+1] = 1
end

But, there seems to be a problem when y_vec is not continuous, say y_vec = [0; 1; 1; 2; 3; 4; 8], using for loop fails !!! How to get around this issue.

Is there a way to solve the above problem using sparse matrix in Julia.

Upvotes: 0

Views: 1505

Answers (1)

Gnimuc
Gnimuc

Reputation: 8566

you can use sparse matrix constructor sparse(I,J,V):

y_vec = [0; 1; 1; 2; 3; 4; 8]
I = collect(1:length(y_vec))
J = y_vec+1
V = ones(length(y_vec))
S = sparse(I,J,V)
full(S)

julia> full(S)
7x9 Array{Float64,2}:
 1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  1.0

Upvotes: 2

Related Questions