Custom error to check stochastic matrix

I would like to write a function that checks whether the rows of a stochastic matrix sum to 1 and throws an error if they do not.

The following code works for a check by hand:

sum(mat,dims = 2)

But this code does not work. It falsely flags all matrixes as not summing to 1, even “good” matrixes.

stoch_mat_check(mat) = any(x -> x != 1.0,sum(mat,dims = 2)) : error("ERROR: rows dont sum one")

mat = [.5,.5]
stoch_mat_check(mat)

Returns

ERROR: rows dont sum one

Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] stoch_mat_check(mat::Vector{Float64})
   @ Main ./In[231]:18
 [3] top-level scope
   @ In[231]:21
 [4] eval
   @ ./boot.jl:373 [inlined]
 [5] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1196

Two points.

  1. This isn’t doing what you think it’s doing:
Julia> mat = [0.5, 0.5]
2-element Vector{Float64}:
0.5
0.5

julia> sum(mat, dims = 2)
2-element Vector{Float64}:
0.5
0.5

julia> mat = [0.5 0.5]
1×2 Matrix{Float64}:
 0.5  0.5

julia> sum(mat; dims = 2)
1×1 Matrix{Float64}:
 1.0

Note the different definition of mat.

  1. Never use exact comparisons.
julia> 3 * 0.1 == 0.3
false

Use isapprox(3 * 0.1, 0.3) instead: Getting started with Julia · JuMP

“mat” is vector, not matrix, it will acts like a row vector.

julia> mat
2-element Vector{Float64}:
 0.5
 0.5

julia> sum(mat, dims=2)
2-element Vector{Float64}:
 0.5
 0.5

You can initialize a matrix with spaces instead of comma.

julia> mat = [0.5 0.5]
1×2 Matrix{Float64}:
 0.5  0.5

julia> stoch_mat_check(mat)
false
2 Likes

Thank you! But this still returns the error:

#quick check: 
stoch_mat_check(mat) = any(x -> !(isapprox(x,1)),sum(mat,dims = 2)) : error("ERROR: rows dont sum one")

mat = [.5 .5]
stoch_mat_check(mat)

oh yea, I forgot to mention, I think you meant to use && short-circuit.

stoch_mat_check(mat) = any(x -> x != 1.0,sum(mat,dims = 2)) && error("ERROR: rows dont sum one")

If you want ternary, you are missing the ? and statement for true

stoch_mat_check(mat) = any(x -> x != 1.0,sum(mat,dims = 2)) ? error("ERROR: rows dont sum one") : print("all good")
2 Likes

oh thank you, that’s it!! This is my first time making an error function.

1 Like