How to build this sparsematrix in Julia

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:

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:

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.

2 Likes