How to reference equations from the workspace into the function file?

Hello all, I am now having problems about referencing equations.
For example:
clear;close all;clc;
x0=[-1,1];
[x,fval]=fmincon(@objfun,x0);
and the objfun function file is:
function f=objfun(x)
f=exp(x(1))*(4*x(1)^2+2*x(2)^2+4*x(1)*x(2)+2*x(2)+1);
end
The code runs and works.
However if I do this:
clear;close all;clc;
x0=[-1,1];
f="exp(x(1))*(4*x(1)^2+2*x(2)^2+4*x(1)*x(2)+2*x(2)+1)"
f=str2sym(f);
[x,fval]=fmincon(@objfun,x0)
And try to reference f in the function file:
function f=objfun(x)
f=evalin('base','f');
end
This will generate an error:
Error using fmincon (line 694)
FMINCON requires all values returned by functions to be of data
type double.
I want to reference the expressions in the function file as I have 28 symbolic equations obtained from previous code. Copying all the equations will be laborious for me and if any coefficients of the equations changed I will have to recopy again...

Answers (1)

Use str2func, not str2sym, and pass that to fmincon directly:
f="exp(x(1))*(4*x(1)^2+2*x(2)^2+4*x(1)*x(2)+2*x(2)+1)";
f=str2func("@(x)" +f);
[x,fval]=fmincon( f,x0)

2 Comments

Thank you Matt. Yes this works, but this is not a way of referencing the equation from the function file... My real situation makes me have to reference it from the function file
You should elaborate on why you think you need a function file at all. In your post, you seemed to be saying that you already have the function in equation form.
In general, though, if the objective function requires any Matlab variables that are fixed for the problem but may change from problem to problem, then the way to make them accessible in an objective function file is using nested or anonymous functions, as described here.
Fixed problem variables that you pass to the objective can include symbolic variables and equations. Note however, that it will be inefficient to use the equations in symbolic form. It is advisable to use matlabFunction to pre-convert them to a non-symbolic function handle.

Sign in to comment.

Products

Release

R2018a

Asked:

on 10 Jul 2018

Edited:

on 11 Jul 2018

Community Treasure Hunt

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

Start Hunting!