Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Help with anonymous function, fsolve, and str2func

156 views
Skip to first unread message

Alicia

unread,
Jun 28, 2012, 10:55:07 AM6/28/12
to
I'm trying to write a code that uses fsolve to solve for missing variables in a set of non-linear equations. The problem is that it will be different variables that are missing for each run. So I'm using a loop to determine which variable is missing, and then putting that into a string. Then using the str2func function to turn the function with the equations (@isp) into an anonymous function that is only a function of the missing input (th).

This is the code:
f = str2func('@(th)isp(n,m,th)');
th = fsolve(f,0);

This is the error:
??? Undefined function or variable 'n'.
Error in ==> @(th)isp(n,m,th)
Error in ==> fsolve at 253
fuser = feval(funfcn{3},x,varargin{:});

I hope I explained that well enough. Please help!

Thanks!

Matt J

unread,
Jun 28, 2012, 2:59:10 PM6/28/12
to
"Alicia " <ast...@asdl.gatech.edu> wrote in message <jshr8b$lbl$1...@newscl01ah.mathworks.com>...
>
> This is the error:
> ??? Undefined function or variable 'n'.
> Error in ==> @(th)isp(n,m,th)
> Error in ==> fsolve at 253
> fuser = feval(funfcn{3},x,varargin{:});
>
> I hope I explained that well enough. Please help!
================

The variable 'n' did not exist at the time you defined the anonymous function. Here's an example of the same error in isolation from other code,

>> clear all; f=@(a) sin(a+b); f(1)
Undefined function or variable 'b'.

Error in @(a)sin(a+b)

Matt J

unread,
Jun 28, 2012, 3:02:09 PM6/28/12
to
"Alicia " <ast...@asdl.gatech.edu> wrote in message <jshr8b$lbl$1...@newscl01ah.mathworks.com>...
>
> This is the code:
> f = str2func('@(th)isp(n,m,th)');
> th = fsolve(f,0);

Instead of STR2FUNC, I think you'll have to use EVAL:

f = eval('@(th)isp(n,m,th)');

Alicia

unread,
Jul 2, 2012, 12:45:07 PM7/2/12
to
"Matt J" wrote in message <jsi9nh$ro2$1...@newscl01ah.mathworks.com>...
EVAL worked great! Thank you!
0 new messages