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

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

问题描述

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

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,...,则可能需要一个大批. 在茱莉亚,这可能看起来像这样,(但请注意,我不知道我在用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.

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

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