问题
The symbolic expression below is one example out of many expressions
expr = x + (x/z)*log(C + x/y);
for the above expression I need to solve as below
STEP 1:
var1 = x/y % accessing expression one operation at a time
result1 = applySomeFunction(var1)
STEP 2:
var2 = var1+C
result2 = someConstantValue*result1+ applySomeFunction(var2);
STEP 3:
var3 = log(var2)
result3 = someConstantValue*result2 + applySomeFunction2(var3);
Step4:
var4 = var3*x
result4 = someConstantValue*result3 + applySomeFunction2(var34);
. . . until the end of expression.
Is there a way to extract and access symbolic subExpressions based upon operation?
I tried by converting into string but there are so many masking error with usage of parenthesis and not so efficient.
回答1:
symbolic variables are defined with syms command.
MATLAB code:
syms x y z C v1 v2 v3 v4;
v1 = x/y;
v2 = v1+C;
v3 = log(v2);
v4 = v3*x;
.......
or if u just need expr then,
syms x y z C expr;
expr = x + (x/z)*log(C + x/y);
And then to explore those variables: e.g (x=1,y=2,z=3,C=4 in expr)
subs(expr,{x,y,z,C},{1,2,3,4});
This will give:
expr = 1 + (1/3)*log(9/2);
But I would recommend you use the anonymous function instead if you don't want to use MATLAB inbuilt differentiation or Integration or some other symbolic functions. They are much faster and easy to work with.
expr = @(x,y,z,C) x + (x/z)*log(C + x/y);
expr(1,2,3,4)
This will give result: 1.501359...
来源:https://stackoverflow.com/questions/52272042/how-to-access-symbolic-expression-based-on-arithmetic-operators-matlab