英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论