How to replace variables in symbolic function with values from a vector

I am working on a simple optimization code that has to account for varying number of equations. Since the existence of a type of equation adds one more variable, and the code cannot know how many it will encounter, it creates variables based on the input.
For example, the symbolic function might be:
L = L(x1, x2, v1)
L = L(x1, x2, v1, u1, u2)
...
x = sym('x',[2 1]) % variables of objective function
v = sym('v',[p 1]) % input requires p more variables
v = sym('u',[m 1]) % input requires m more variables
k = vertcat(x,v,....) % all variables based on input
The code does symbolic differentiation on k(i), and after manipulations obtains a final function.
result = (x1 - 3)^2 + (x2 - 3)^2 - v1*(3*x2 - x1 + 1) + u1*(s1^2 + x1 + x2 - 4)
The code is able to calculate values for all of the variables that exist for a particular case.
k = [x1,x2, v1, u1, s1] = [ 13/4, 3/4, -5/4, 3/4, 0]
However, I was unable to substitute these values back in the symbolic functions "L", and "result" to calculate their actual numeric values at this point, and for plotting them.
I appreciate any help on this.

 采纳的回答

You probably want the function
subs()

5 个评论

Thank you for the response Marc. I tried subs() but failed. Since I do not know which variables I will end up I cannot hard code them in subs(). I tried subs(result, k) but failed. k contains all symbolic variables that are present. A for loop with subs(result, k(i)) was also failed.
Have you tried expressing result using the symbolic vectors and not the values? Something like
xx = [x; v; u]
result = (xx(1) - 3)^2 + (xx(2) - 3)^2 - xx(3)*(3*xx(2) - xx(1) + 1) + xx(4)*(s(1)^2 + xx(1) + xx(2) - 4) %I don't know what s1 is. Is that a sym too?
Since result uses three arrays of syms, there is no way for Matlab to know which variables in result correspond with which sym in k.
How do I do this programmatically?
s1 is also a symbolic variable. So, if I have a result function like this at the workspace
result = x1^2 + x2^2 + v1 + v2 + u1 + s1
% then the variables are
xx = [x1;x2;v1;v2;u1;s1];
Number of u, v, and s variables depend on the particular problem that user inputs. I calculate the xx matrix values using solve(), and get the following which I convert to numerical values.
xx_result = [ 1, 2, 3, 4, 5, 6]
So, how do I programmatically substitude these into xx and calculate result function's value? I thought I could do
xx = xx_result;
and this would make symbolic values equal to their corresponding values. X1 = 1, x2 = 2, ... And then just type result and get its value. That did not work...
Thank you.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by