Best way to initialize a sparse matrix with some non-zero columns

Hello,

I would like to initialize a sparse array A of size N \times Nx, for which only the columns in dims are non-zeros.

How can I improve this code?

using LinearAlgebra
using SparseArrays 

N = 200
Nx = 20

dim = [1; 2; 5; 8; 10; 14; 17; 20]

A  = sparse(repeat(1:N, length(dim)), vcat([i*ones(Int64, N) for i in dim]...), ones(N*length(dim)), N, Nx)
julia> A = spzeros(N, Nx)
200×20 SparseMatrixCSC{Float64,Int64} with 0 stored entries

julia> A[:, dim] .= 1

maybe ?

2 Likes

Thank you for your answer, that’s much better. From what I understand, we don’t want to add extra non-zero entries in a sparse matrix. I guess the overhead is negligible in this case.