This is a classic pattern for sparse matrices – constructing them by
assignment is very inefficient, so it's much better to construct the I, J,
V vectors and then call sparse. It's often more efficient to use findnz to
get I, J, V, do some operations on these vectors, and call sparse to
construct a new matrix, than it is to directly operate on the sparse matrix.

On Mon, Feb 1, 2016 at 9:20 PM, Gabriel Goh <[email protected]> wrote:

> Thanks! This triplet solution was a miracle
>
>
> On Monday, February 1, 2016 at 1:46:27 AM UTC-8, Kristoffer Carlsson wrote:
>>
>> At computer now.
>>
>> Something like this:
>>
>> function f(k)
>>     I, J, V = Int[], Int[], Float64[]
>>     for i = 1:k
>>         idxs = (i-1)*2 + 1:i*2
>>         for i in idxs, j in idxs
>>             push!(I, i)
>>             push!(J, j)
>>             push!(V, rand())
>>         end
>>     end
>>     return sparse(I,J,V)
>> end
>>
>> @time f(10000)
>> 0.001932 seconds (71 allocations: 4.986 MB)
>>
>>
>>
>> On Monday, February 1, 2016 at 9:25:22 AM UTC+1, Kristoffer Carlsson
>> wrote:
>>>
>>> Create the vectors I J V which holds the nonzero rows, columns and
>>> values respectively and then call sparse(I, J, V).
>>
>>

Reply via email to