Did you run the test in global scope? Does the following code show the same 
performance characteristics?

=============
function test1(A, s, x, y)
    for i=1:length(A) 
        if abs(A[i])>0. 
            val += (A[i] - s) * (x + y) 
        end
    end
end
@time test1(A, s, x, y)
------------
function test2(A, s, x, y)
    iA = findn(A) 
    for i=1:length(iA) 
        val += (A[iA[i]] - s) * (x + y) 
    end
end
@time test2(A, s, x, y)
============= 


kl. 08:21:40 UTC+2 fredag 17. oktober 2014 skrev K leo følgende:
>
> I have a sparse array (roughly 1/5 filled say).  If I simply loop 
> through it, it is about 10 times slower than if I loop through only the 
> nonzero elements.  Compare the following codes, the first is 10 times 
> slower, even with the multiplications. 
>
> ============= 
> for i=1:length(A) 
>      if abs(A[i])>0. 
>         val += (A[i] - s) * (x + y) 
>      end 
> end 
> ------------ 
> iA = findn(A) 
> for i=1:length(iA) 
>      val += (A[iA[i]] - s) * (x + y) 
> end 
> ============= 
>

Reply via email to