Julia 在循环中更改名称,使用符号变量 [英] Julia changing name in loop, using symbolic variables

查看:16
本文介绍了Julia 在循环中更改名称,使用符号变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在循环的每次迭代中更改符号变量的名称,然后使用这些符号变量求解方程,例如:

I'd like to change the name of a symbolic variable in each iteration of a loop, and then solve an equation using these symbolic variables e.g:

using SymPy
for i in 1:5
  p{i} = symbols("p"{i}, real=true,positive=true)
  solve(p{i}^2-i^2)
end

所以我希望创建一系列标量符号变量(因为我认为不可能创建向量值符号变量),每个变量都有不同的名称 - p1、p2、p3、p4 和 p5 -然后在方程求解器中使用这些.但是,根据 matlab,花括号表示法似乎不适用于 julia 中的命名.一个快速的谷歌没有提出任何明显的答案.有什么想法吗?

So I'm looking to create a series of scalar symbolic variables (since I don't think it is possible to create a vector valued symbolic variable) each with a different name - p1,p2,p3,p4 and p5 - and then use these in a equation solver. However the curly braces notation does not seem to work for naming in julia as per matlab. A quick google didn't suggest any obvious answers. Any ideas?

推荐答案

在 julia 和大多数计算机语言中,如果你发现自己需要一堆数字变量 x1, x2, x3, ... ,你可能想要一个大批.在 julia 中,这可能看起来像这样,(但请注意,我不知道我在用 SymPy 做什么)

In julia, and in most computer languages, if you find yourself needing a bunch of number variables x1, x2, x3, ... , you probably want an array. In julia this might look like this, (but note that I have no idea what I'm doing with SymPy)

using SymPy
pp=Sym[]
for i in 1:5
    p = symbols("x$i", real=true,positive=true)
    push!(pp,p)
    solve(pp[i]^2-i^2)
end

这里我们以 pp 为空开始,但类型正确;我们将每个符号推到 pp 的末尾;最后我们可以用 pp[i] 找出 pp 的第 i 项,这几乎是你的代码,但没有 shift 键.

Here we start with pp empty, but of the right type; we push each symbol onto the end of pp; finally we can fish out the i'th item of the pp with pp[i], which is almost your code, but without the shift key.

这篇关于Julia 在循环中更改名称,使用符号变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆