Broadcasting trig functions to SparseArrays.SparseMatrixCSC

I have noticed some difference in behaviors when broadcasting trig functions to SparseArrays.SparseMatrixCSC objects. Here is an example.

Let x be a SparseArrays.SparseMatrixCSC{Complex{Float64},Int64} object.
It has 1000 rows and 1000 columns, with 1000 non-zero values on the diagonal.

If I try sin.(x), broadcasting works correctly and the output has only 1000 non-zero values.

However, if I try cos.(x), broadcasting does not work as intended, as the output has non-zero value everywhere in the 1000x1000 array. Why?

cos(0)=1 which means you need to store everything.

1 Like

I see, somehow I thought broadcasting will only apply to non-zero values. Then what would be an appropriate fix to get what I want?

You can explicitly broadcast over the non-zero values, x.nzval.

using LinearAlgebra, SparseArrays
using Random

N = 4
x = sparse(Diagonal(rand(ComplexF64,N)))


@. x.nzval = cos(x.nzval)

println("Broadcast cos")

which prints out


  [1, 1]  =  0.236033+0.346517im
  [2, 2]  =  0.312707+0.00790928im
  [3, 3]  =  0.488613+0.210968im
  [4, 4]  =  0.951916+0.999905im

Broadcast cos

  [1, 1]  =  1.03123-0.0826637im
  [2, 2]  =  0.951534-0.0024332im
  [3, 3]  =  0.902708-0.099765im
  [4, 4]  =  0.895112-0.957115im
1 Like