Function - str2func gives unusual error
Show older comments
[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.
1 Comment
Tazmusica
on 23 May 2011
Accepted Answer
More Answers (1)
Oleg Komarov
on 23 May 2011
Use:
FUN='@(c,ppm)(';
And call:
pdefun([1 1 1],ppm)
My interpretation of the problem is: when you call str2func(FUN), ppm.B11 is not in the private workspace of str2func and thus the anonymous functions considers ppm.B11 as an undeclared constant (bug? unexpected/expected behaviour? Dunno).
When you call pdepe(.), thus ppm.B11 has no value and it throws that error (strange error though).
In anonymous functions the constants take the value they have at the moment the @(.) is created and thus it doesn't search the workspace when executed for the actual value of the constant (this is true also if you update ppm and expect @(.) to reflect this change).
Categories
Find more on Function Handles 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!