MATLAB: Fit and Plot a Polynomial Surface

Curve Fitting Toolboxhorzcat

Allright, the last time i used matlab was two years ago and i almost forgot everything. What i´m trying to do is to plot a x y z matrix and fit it so i get an mathematical formular. So basically what´s done here : https://de.mathworks.com/help/curvefit/polynomial.html#bt9ykh7 "Fit and Plot a Polynomial Surface"
I tried it like this, as i said i haven´t done this in a while so don´t execute me
y1=[1 2 3 4];
x1=[100 200 300 400]';
[x,y]=meshgrid(x,y1);
z=[1.0 1.6 2.0 2.460; 1.0 1.5...
1.8 2.2; 1.0 1.5 1.931 2.2;...
1.1 1.6 2.1 2.4];
fitsurface=fit([x,y],z, 'poly21');
plot(fitsurface, [x,y],z);
And that´s what i get :
Error using fit>iFit (line 135)
X must be a matrix with one or two columns.
Error in fit (line 116)
[fitobj, goodness, output, convmsg] = iFit( xdatain, ydatain, fittypeobj, ...
Error in Matlab_Versuch (line 7)
fitsurface=fit([x,y],z, 'poly21');
I basically know what´s wrong but i can´t fix it.
Thanks

Best Answer

Check spelling... :)
x1=[100 200 300 400]';
[x,y]=meshgrid(x,y1);
You defined x1 but used x as argument instead...
fitsurface=fit([x,y],z, 'poly21')
fit wants vectors, not arrays. Use the Matlab idiom (:) to return all elements of matrix/array as column vector:
x=x(:); y=y(:); z=z(:);
fitsurface=fit([x,y],z, 'poly21')
Somehow the builtin plot doesn't recognize it's a surface and only plots on 2D axis; I had to use scatter3 to show...
Also, it appears the real curvature is in Y but you fit the quadratic in X; looks like should either reverse role of X,Y or use 'poly12' instead of 'poly21'
Related Question