Running sfit (or fit) from command line

7 views (last 30 days)
Richard Arlow
Richard Arlow on 5 Mar 2012
Hi,
I am interested in having MatLab perform surface fitting from the command line to a set of 2D data (O1) with a time and a space input: T (meshgrid matrix) or t (vector) and Y (meshgrid matrix) or y (vector).
Example Code:
step=25;
ymax=500;
t=linspace(1,20,20);
y=-ymax:step:ymax;
[T,Y]=meshgrid(t,y);
size(T)=41 20
length(t)= 20
size(Y)=41 20
length(t)= 41
size(O1)=41 20
I can call the interactive sftool with the following code from the command line:
sftool(T(:),Y(:),O1(:))
In this interactive fit I can create a polynomial fit to the surface using 2 degrees for t and 5 for y (i.e. poly25).
However, I want to be able to write this surface fitting into a for loop to create fits and extract the coefficients of the polynomial fitting for lots of different O1 matrices. I want to automate the surface fitting for lots of O1 matrices then call:
coeff=coeffvalues(sf); %formula, coeffnames, etc.
to obtain the coefficient values.
I have tried the following and have not been able to successfully perform the entire surface fitting from the command line:
ft = fittype( 'poly25' );
opts = fitoptions( ft );
opts.Weights = zeros(1,0);
opts.Normalize = 'on';
[fitresult, gof] = fit( [t, y], O1, ft, opts );
With Error:
??? XDATA must be a matrix with one to two columns.
Error in ==> fit at 115
errstr = handleerr('curvefit:fit:xDataMustBeColumnVector',
...
[fitresult, gof] = fit(T(:),Y(:),O1(:), ft, opts );
With Error:
??? Error using ==> fittype.fittype>fittype.fittype at 212
First input argument must be a string or cell array.
Error in ==> fit at 147
model = fittype( fittypeobj );
I have also tried calling sfit (instead of fit) and changing the order and type of input (t,y instead of T,Y - i.e. meshgrid matrix or vector) and cannot get this to work for me.
Please let me know at your earliest convenience what would be the best way to perform the surface fitting outside of the interactive sftool for 2D Data with 2 Inputs.
Thanks,
Rick

Answers (1)

Tom Lane
Tom Lane on 5 Mar 2012
A good tip in cases like this is to use the "generate code" feature to see what the cftool GUI is doing. If you do that, you'll find a line like this:
[xData, yData, zData] = prepareSurfaceData(x,y,z);
This is taking a matrix z, and vectors (x,y) that correspond to the rows and columns of z, and converting that into something that the fit command is expecting. The outputs are vectors suitable for use with the fit command, something like:
fit([xData, yData], zData, 'poly25')

Community Treasure Hunt

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

Start Hunting!