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

**URL:** <https://discourse.julialang.org/t/best-way-to-initialize-a-sparse-matrix-with-some-non-zero-columns/45856>\
**Category:** Performance\
**Tags:** question\
**Created:** [August 31, 2020, 6:58pm UTC](https://discourse.julialang.org/t/best-way-to-initialize-a-sparse-matrix-with-some-non-zero-columns/45856 "2020-08-31T18:58:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mleprovost](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mleprovost/32/7166_2.png) [@mleprovost](https://discourse.julialang.org/u/mleprovost)\
**Post date:** [August 31, 2020, 6:58pm UTC](https://discourse.julialang.org/t/best-way-to-initialize-a-sparse-matrix-with-some-non-zero-columns/45856/1 "2020-08-31T18:58:30Z")

</div>

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?

```julia
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)

```

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [August 31, 2020, 10:03pm UTC](https://discourse.julialang.org/t/best-way-to-initialize-a-sparse-matrix-with-some-non-zero-columns/45856/2 "2020-08-31T22:03:54Z")

</div>

```julia
julia> A = spzeros(N, Nx)
200×20 SparseMatrixCSC{Float64,Int64} with 0 stored entries

julia> A[:, dim] .= 1

```

maybe ?

---

<div class="post-metadata">

**Author:** ![mleprovost](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mleprovost/32/7166_2.png) [@mleprovost](https://discourse.julialang.org/u/mleprovost)\
**Post date:** [August 31, 2020, 10:41pm UTC](https://discourse.julialang.org/t/best-way-to-initialize-a-sparse-matrix-with-some-non-zero-columns/45856/3 "2020-08-31T22:41:42Z")

</div>

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.
