# How to build this sparsematrix in Julia

**URL:** https://discourse.julialang.org/t/how-to-build-this-sparsematrix-in-julia/84608
**Category:** General Usage
**Tags:** question, linearalgebra, sparse
**Created:** [July 21, 2022, 9:20pm UTC](https://discourse.julialang.org/t/how-to-build-this-sparsematrix-in-julia/84608 "2022-07-21T21:20:02Z")
**Posts on this page:** 1
**Showing post:** 9

<div class="post-metadata">

### Author: ![acxz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/acxz/32/16759_2.png) [@acxz](https://discourse.julialang.org/u/acxz)
#### Post date: [July 23, 2022, 2:03am UTC](https://discourse.julialang.org/t/how-to-build-this-sparsematrix-in-julia/84608/9 "2022-07-23T02:03:30Z")

</div>

It seems like you are only changing the data entries of the sparse matrix during the loop. Hence, you can precompute the data entries, `IK`, and then create the sparse matrix.

Simplifying your math in the code, we can the following simplification of the for loop:

```julia
Ik = [10.0, 12.0, 23.0, 34.0, 45.0] # variable
Ik .*= 2.0^100 * 2 * prod(1:100.0)
F = sparse(1:5, 11:11:55, Ik)

```

Timing gives the following:

```julia
129.232 μs (2447 allocations: 354.84 KiB) # Original code
560.737 ns (13 allocations: 1.80 KiB) # The simplified code above

```

Try to obtain the values of the final sparse matrix and then create a sparse matrix. And when obtaining the values of the final sparse matrix, simplify the mathematical expression.

Note: as your code is posted you will get integer overflow and the resulting matrix will be 0s. Using `prod(1:100.0)` instead of `prod(1:100)`, 2.0^100 instead of 2^100, and Ik = [10.0, …] instead of [10, …] ensures that floats are used and thus the product can be computed successfully, without overflow. (Floats can represent larger numbers in memory compared to Ints)

Since `Nh` is fixed you can also use a UnitRange for it instead of allocating memory for the array. `[11, 22, 33, 44, 55]` turns into `11:11:55`.

---

_[View the full topic](https://discourse.julialang.org/t/how-to-build-this-sparsematrix-in-julia/84608)._
