Avoid unnecessary computations with (sparse) Arrays

Hi,

I would like to avoid unnecessary computations in computing shifts of matrices like for example 0*I + 1*J. I thought about the code below, but this is not really a viable strategy because I would like to dispatch on the value y = 1. Is there a better way to do this?

Thank you for your suggestions,

Best.

using LinearAlgebra, SparseArrays
const Jtmp = sprand(10^4,10^4,0.001)
f(x,y) = x * I + y .* Jtmp
f(x::Nothing, y) = y .* Jtmp
f(x::Nothing, y::Nothing) = Jtmp

Why do you need dispatch? Your matrix is large I assume, so nothing wrong with a good old if statement, hardly costs you anything. And if y is a constant in your code, constant propagation may even kick in.

2 Likes

I agree, thank you for your suggestion.