Convert a Matrix{Num} to Matrix{Int64} after substituting all symbolic variables in Julia

huangapple go评论57阅读模式
英文:

Convert a Matrix{Num} to Matrix{Int64} after substituting all symbolic variables in Julia

问题

使用symbolics.jl时,具有变量的矩阵的类型为Matrix{Num}。然而,即使替换了所有变量,类型仍然是Matrix{Num} - 如何将其转换为Matrix{Int64}

考虑以下示例:

using Symbolics
@variables t

symbolic_mtx = [t 2; 3 4] # 这个矩阵具有符号项
println(typeof(symbolic_mtx)) # 打印Matrix{Num},如预期

# 现在我们将t=1代入
numeric_mtx = substitute(symbolic_mtx, Dict(t => 1))
println(typeof(numeric_mtx)) # 仍然打印Matrix{Num}!

这使用了像这里建议的方式的substitute函数,但不起作用 - 类型仍然是Matrix{Num}

英文:

When using symbolics.jl, matrices with variables are of type Matrix{Num}. However, even after substituting all variables, the type is still Matrix{Num} -- How can I convert this into a Matrix{Int64}?

Consider the following example:

using Symbolics
@variables t

symbolic_mtx = [t 2; 3 4] # this matrix has a symbolic entry
println(typeof(symbolic_mtx)) # prints Matrix{Num}, as expected

# now we plug t=1 in
numeric_mtx = substitute(symbolic_mtx, Dict(t => 1))
println(typeof(numeric_mtx)) # still prints Matrix{Num}!

This uses substitute as recommended here, but does not work -- the type is still Matrix{Num}.

答案1

得分: 1

我找到了解决方案:在替换后,需要使用 Symbolics.value 来引用这些值。对于问题中的矩阵情况,我们需要进行广播,以便以下操作正常运行:

numeric_mtx = Symbolics.value.(substitute(symbolic_mtx, Dict(t => 1))) 
println(typeof(numeric_mtx)) # 仍然打印 Matrix{Int64}
英文:

I found the solution: After substituting, one needs to reference the values by using Symbolics.value. In the case of a matrix as in the question, we need to broadcast, so that the following works:

numeric_mtx = Symbolics.value.(substitute(symbolic_mtx, Dict(t => 1))) 
println(typeof(numeric_mtx)) # still prints Matrix{Int64}

huangapple
  • 本文由 发表于 2023年6月12日 04:11:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定