Convert matrix elements from Int to Float

If I have the following matrix

sparse([1, 2, 3, 4, 1, 2, 4, 1, 3, 4, 5, 1, 2, 3, 4, 5, 3, 4, 5], [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5], [3, -1, -1, -1, -1, 2, -1, -1, 3, -1, -1, -1, -1, -1, 4, -1, -1, -1, 2], 5, 5)

how I can convert the matrix elements to float instead of integer? something like this:

sparse([1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 4.0, 1.,0 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 4.0, 5.0], [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0],[3.0, -1.0, -1.0, -1.0, -1.0, 2.0, -1.0, -1.0, 3.0, -1.0, -1.0, -1.0, -1.0, -1.0, 4.0, -1.0, -1.0, -1.0, 2.0], 5.0, 5.0)

If A is your array, use float.(A).

1 Like

Alternatively, use the type you want in front of the values vector (3rd argument). For example, for Float64 values use

sparse([i1,i2,...],[j1,j2,...],Float64[v1,v2,...],m,n)

Note that you must use an integer type for the i and j vectors, as well as the dimensions m and n. Floating point values are only acceptable in the v argument. If you have the arguments as vectors, then sparse(i,j,float.(v),m,n) will work. If you already have the matrix built, then use the above suggestion of float.(A) where A is your matrix. If you specifically want some type like Float32 or BigFloat, replace float in the above calls with those instead.

You don’t need the dot; float(A) works too, and can be more efficient (e.g. it doesn’t make a copy if A is already a floating-point array, and has specialized methods for particular array types). See also the discussion in Deprecate vectorized float methods in favor of compact broadcast syntax by Sacha0 · Pull Request #18495 · JuliaLang/julia · GitHub

In particular, the original question in this thread is about sparse matrices, and float(A) has a specialized method for SparseMatrixCSC.

You can do slightly better if you are willing to share the same row and column index vectors as the original array, rather than making a copy as float(A) does, in which case you can do:

SparseMatrixCSC(size(A)..., getcolptr(A), rowvals(A), float(nonzeros(A)))

(Honestly, I think that this should be the default behavior of float(A) for sparse matrices, since float(A) does not necessarily make a copy anyway: float(S) and complex(S) should not copy data unnecessarily by stevengj · Pull Request #340 · JuliaSparse/SparseArrays.jl · GitHub)

1 Like