Evaluate a function of symbolic variables
2 views (last 30 days)
Show older comments
Hassan Benchekroun
on 15 Oct 2020
Commented: Hassan Benchekroun
on 22 Oct 2020
I created a function (PV) that depends on a symbolic vector (q1,q2,q3). I would like to evaluate it at some value of the vector but it keeps giving me the general expression in terms of the symbolic vector instead of giving a number. In the end I would like to use fminsearch to minimize the function PV wrt to the symbolic vector (q1,q2,q3).
Thanks in advance.
T=3;
Q = sym('q', [1 T]);
p=1;
c=4;
delta=0.05;
rho=1/(1+delta);
R0=1;
[NETR,Res,PV]=fnsum(T,Q,R0,c,rho,p);
obj = @(q1,q2,q3) -PV;
obj(0.1,0.1,0.1)
function [netrev,R,summm] = fnsum(t,Quant,R1,c,rho,p)
R = sym(1:t+1);
netrev = sym(1:t);
Quant = sym('q', [1 t]);
R(1)=R1;
for i=1:t
netrev(i)= p .* Quant(i) -(c /2).*(Quant(i) .^2)./R(i)
R(i+1)=R(i)-Quant(i);
end
n=1:t;
summm = -sum(((rho).^(n-1)).*(netrev(n)))
end
0 Comments
Accepted Answer
Steven Lord
on 15 Oct 2020
Use subs to substitute values for the symbolic variables in your expression.
When you go to use your symbolic expression in fminsearch convert it to a function handle using matlabFunction or make certain that the function that evaluates your symbolic expression returns a double array not a symbolic one. The double function will help you with that.
3 Comments
Steven Lord
on 20 Oct 2020
This line of code does not make the same thing as three inputs to a function:
Q0 = 0.1, 0.1, 0.1;
When you run this code you'll see something like:
Q0 =
0.1
ans =
0.1
That line is not one command, it's three.
Q0 = 0.1
0.1
0.1;
The first of those commands assigns the value 0.1 to Q0 and displays it.
The second of those commands assigns the value 0.1 to ans and displays it.
The third of those commands assigns the value 0.1 to ans and does not display it. You can see this with a slightly modified version of the example:
>> Q0 = 0.1, 0.2, 0.3;
Q0 =
0.1
ans =
0.2
>> ans
ans =
0.3
There is a way to do what you're asking, but probably the easiest way to explain is to create a wrapper around your function like this:
f = @(x1, x2) x1 + x2.^2;
g = @(x) f(x(1), x(2));
f(4, 5)
g([4, 5])
More Answers (0)
See Also
Categories
Find more on Assumptions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!