How can I create a MATLAB file function from a cfit object created by the Curve Fitting Toolbox?

I have created a cfit object using the Curve Fitting Toolbox. Now, I would like to save this cfit object as a MATLAB file rather than having to regenerate it.

 Accepted Answer

There is no function in the Curve Fitting Toolbox for creating a MATLAB file function from a cfit object.
You can use the following code, which creates MATLAB file functions from cfit objects. Save this code in an file named cfit2mfile.m:
function F = cfit(cfobj,FName)
%CFIT2MFILE Converts a cfit object to a MATLAB file.
% CFIT2MFILE(cfobj,fname) converts the cfit object cfobj to a MATLAB file
% defined in fname.
%
% F = CFIT2MFILE(cfobj,fname) returns a function handle in F.
%
% Example:
% load census
% [fit1,gof1,out1] = fit(cdate,pop,'poly2');
% F = cfit2mfile(fit1,'censusfitfcn')
[fdir fname fext] = fileparts(FName);
if ~strcmp(fext,'m')
FName = [fdir fname '.m'];
end
body = [];
header = ['function X = ' fname '('];
func = ['X = ' formula(cfobj) ';'];
args = argnames(cfobj);
for n = 1:length(args)
try
v = getfield(cfobj,args{n});
body = [body args{n} ' = ' num2str(v) '; '];
catch
header = [header args{n} ','];
end
end
header(end) =')';
[fID,message] = fopen(FName,'w');
if fID~=1
fprintf(fID,'%s\n%s\n%s',header,body,func);
fclose(fID);
clear(FName);
if nargout>0
F = str2func(fname);
end
else
error(message)
end
An example of its use is given in the help comments.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!