MATLAB: Function – str2func gives unusual error

functionjacobianeststr2func

[EDIT: 20110523 11:28 CDT – reformat – WDR]
Background:
I have written a script that takes user input for a fit of a sum of functions. Using this, the fit is performed using separable least squares. The fit is obtained flawlessly. The problem arises in the determination of parameter error.
Problem:
Shown below is the section of the program wherein the issue occurs. nfunct is defined previously in the script and corresponds to the user inputted number functions in the sum of functions for the overall fit. ppm.B11 is a matrix of values that resulted from data collection. For the sake of example, let ppm.B11=[0;1;2;3;4;5;6;7;8;9;10]
FUN='@(c)(';
for s=1:1:nfunct-1
FUN=[FUN 'c(' num2str(3.*(s-1)+1) ').*(c(' num2str(3.*(s-1)+2) ').^2)./((ppm.B11(:,' num2str(specnum) ')-c(' num2str(3.*(s-1)+3) '))+c(' num2str(3.*(s-1)+2) '))+'];
end
FUN=[FUN 'c(' num2str(3.*(nfunct-1)+1) ').*(c(' num2str(3.*(nfunct-1)+2) ').^2)./((ppm.B11(:,' num2str(specnum) ')-c(' num2str(3.*(nfunct-1)+3) '))+c(' num2str(3.*(nfunct-1)+2) '))'];
FUN=[FUN ')'];
pdefun=str2func(FUN);
When I ask MatLab to output pdefun, I get the following:
pdefun =
@(c)(c(1).*(c(2).^2)./((ppm.B11(:,1)-c(3))+c(2)))
This looks as I would have expected. However, when I type in pdefun([1 1 1]), I get the following error:
??? The class "ppm" is undefined.
Perhaps Java is not running.
Error in ==>
@(c)(c(1).*(c(2).^2)./((ppm.B11(:,1)-c(3))+c(2)))
Interestingly, if I type out (or copy and paste from the output when I type "pdefun" alone) in the following manner:
pdefun=@(c)(c(1).*(c(2).^2)./((ppm.B11(:,1)-c(3))+c(2)))
followed by: pdefun([1 1 1]), I get:
ans =
Inf
1.0000
0.5000
0.3333
0.2500
0.2000
0.1667
0.1429
0.1250
0.1111
0.1000
Any ideas why this might be the case?? Thanks.

Best Answer

What version of MATLAB are you using?
As a workaround, this will produce your desired results. Instead of:
pdefun=str2func(FUN); % Not working...
use this:
eval(['pdefun = ',FUN]) % This works...
For example:
nfunct = 1;
specnum = 1;
ppm.B11=[0;1;2;3;4;5;6;7;8;9;10];
FUN='@(c)(';
for s=1:1:nfunct-1
FUN=[FUN 'c(' num2str(3.*(s-1)+1) ').*(c(' num2str(3.*(s-1)+2),...
').^2)./((ppm.B11(:,' num2str(specnum) ')-c(',...
num2str(3.*(s-1)+3) '))+c(' num2str(3.*(s-1)+2) '))+'];
end
FUN=[FUN 'c(' num2str(3.*(nfunct-1)+1) ').*(c(',...
num2str(3.*(nfunct-1)+2) ').^2)./((ppm.B11(:,',...
num2str(specnum) ')-c(' num2str(3.*(nfunct-1)+3),...
'))+c(' num2str(3.*(nfunct-1)+2) '))'];
FUN=[FUN ')'];
eval(['pdefun = ',FUN,';'])
% pdefun=str2func(FUN);
pdefun([1 1 1])
ans =
Inf
1
0.5
0.33333
0.25
0.2
0.16667
0.14286
0.125
0.11111
0.1
Related Question