5

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

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?

  • I'm not sure what you are trying to do here. Do you want to store a new value in an array `p` on each iteration? – spencerlyon2 Jun 23 '15 at 12:29
  • Fair point. I've edited my question to clarify hopefully - I'm looking to create a number of symbolic scalar variables and then use these in an equation solver. The curly braces are used in matlab to name variables in a loop i.e. p{i} when i =1 refers to a variable called p1. – David Zentler-Munro Jun 23 '15 at 13:14
  • 2
    Using a comprehension should work: `xs=[symbols("x$i", real=true, positive=true) for i in 1:5]`. There is a somewhat similar example in the [docs](https://github.com/jverzani/SymPy.jl/blob/master/examples/tutorial.md) under `solve` – jverzani Jun 23 '15 at 13:45
  • I'm really confused by the `p{i}` and `"p"{i}` pseudo-syntax. What is it supposed to mean? – StefanKarpinski Jun 23 '15 at 14:44
  • Ha yes, I guess that's because I don't know what the correct syntax is, hence the question. I am trying to create new variables with different names in a loop: p1, p2, p3 etc. In matlab this is done with the curly bracket notation indicated (http://uk.mathworks.com/matlabcentral/answers/26256-change-name-of-variable-at-each-iteration-of-a-for-loop). Jverzani's answer looks helpful - I'll try that out and get back to you all. – David Zentler-Munro Jun 24 '15 at 16:05

1 Answers1

3

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

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.