Assign values to variables in a loop

5 次查看(过去 30 天)
syms a [1 n];
...
for i=1:n-1
...
a(i+1) = rhs(isolate(eqn,a(i+1)));
a(i+1);
end
I'm trying to assign the expression rhs(isolate(eqn,a2)) to the symbolic variable a2, rhs(isolate(eqn,a3)) to a3, up to an.
I have absolutely no idea how to do this. a(i + 1) assigns the value to the array a, rather than the variable in a(i + 1). If I change i=1:n-1 to i=2:n and put ai, it only assumes ai to be some other variable, rather than replacing i with its value and referring to a2 or a3 or whatever.
What I'd like is for a(i + 1) to refer to the actual variable at that index location, rather than referring to the index location itself. Thing is, it actually does get a2 and a3 etc. in the isolate equation, but it doesn't on the left side???
  2 个评论
madhan ravi
madhan ravi 2019-4-27
编辑:madhan ravi 2019-4-27
What do you mean by "Assign values to variables in a loop" ?
What is your question?
What are you trying to do?
What are the inputs?
What is the desired output?
Where is the example of your illustration?
Is this a homework?
Lucian Williams
Lucian Williams 2019-4-27
The line of code
syms a [1 n];
creates symbolic variables a1, a2, a3, ... an
as well as an array a that contains all of those symbolic variables like so:
[a1 a2 a3 ... an]
I want to set
a2 = rhs(isolate(eqn,a2));
a3 = rhs(isolate(eqn,a3));
an = rhs(isolate(eqn,an));
However, since n is an unknown integer, I cannot simply write n lines of code to perform this action.
Instead, I use a for loop to assign the values.
However,
a(i+1) = rhs(isolate(eqn,a(i+1)));
only replaces the variables in a with new expressions, leaving a2, a3, ... an completely unchanged.
I want the new expression to be assigned to a2, a3, ... an instead of just the array a.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2019-4-27
We recommend against this. Dynamically assigning to full variables is trouble prone, and would tend to contribute to the confusion between variables at the MATLAB level and variables with the same name that exist in the symbolic engine.
You would be better off using subs(). One way would be to keep a cell array of symbolic variables (not a normal vector, a cell), and a another cell of corresponding values and then subs() in appropriate fragments using the subs(expression, cell, cell) calling syntax.
Another approach is to keep a scalar struct with one field per variable name with corresponding value set, and then use the subs(expression, struct) calling syntax. (Note: I recently found problems in the case where a struct member was empty even if that variable was not being substituted.)

更多回答(0 个)

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by