tryingtosolve
tryingtosolve

Reputation: 803

Julia - Preallocating for sparse matrices

I was reading about preallocation from Performance Tips and it has this example:

function xinc!(ret::AbstractVector{T}, x::T) where T
    ret[1] = x
    ret[2] = x+1
    ret[3] = x+2
    nothing
end

function loopinc_prealloc()
    ret = Array{Int}(3)
    y = 0
    for i = 1:10^7
        xinc!(ret, i)
        y += ret[2]
    end
    y
end

I see that the example is trying to change ret which is preallocated. However, when I tried the following:

function addSparse!(sp1, sp2)
    sp1 = 2*sp2
    nothing
end

function loopinc_prealloc()
    sp1 = spzeros(3, 3)
    y = 0
    for i = 1:10^7
        sp2 = sparse([1, 2], [1, 2], [2 * i, 2 * i], 3, 3)
        addSparse!(sp1, sp2)
        y += sp1[1,1]
    end
    y
end

I don't think sp1 is updated by addSparse!. In the example from Julia, function xinc! modifies ret one by one. How can I do the same to a sparse matrix?

In my actual code, I need to update a big sparse matrix in a loop for the sake of saving memory it makes sense for me to preallocate.

Upvotes: 0

Views: 519

Answers (1)

Michael K. Borregaard
Michael K. Borregaard

Reputation: 8044

The issue is not that the Matrix is sparse. The issue is that when you use the assignment operator = you assign the name sp1 to a new object (with value 2sp2), rather than updating the sp1 matrix. Consider the example from performance tips: ret[1] = x does not reassign ret it just modifies it's elements. Use the .= operator instead to overwrite all the elements of a container.

Upvotes: 2

Related Questions