Hi Marco,
From what I understand you are trying to generate an autonomous function that fits a polynomial to a set of data points. The polynomial has a variable number of coefficients, which depends on the size of the input data. You have provided a MATLAB code that generates the input data and plots the results and asking for a way to generate an autonomous function that can be used to evaluate the polynomial at any point, without having to recompute the polynomial coefficients every time.
You can use the “polyfit” function to fit the coefficients of the polynomial.
% generate grid
N = 2;
x = cheby(N);
y = cheby(N);
[X,Y] = meshgrid(x,y);
% create first and second derivative in 1 dimension
D1x = Du(x);
D1y = Du(y);
% testdata
[Z, ZxAna, ZyAna] = fAnalytic(X,Y);
% generate numerical result
ZxNum = reshape(kron(D1x,diag(ones(N+1,1)))*Z(:),N+1,[]);
ZyNum = reshape(kron(diag(ones(N+1,1)),D1y)*Z(:),N+1,[]);
% generate high resolution output
N2 = 65;
x2 = linspace(-1,1,N2);
y2 = linspace(-1,1,N2);
[X2,Y2] = meshgrid(x2,y2);
[~, ZxAna2, ZyAna2] = fAnalytic(X2,Y2);
% fit coefficients of polynomial
p = polyfit([X(:), Y(:)], ZxNum(:), (N+1)^2-1);
fAuto = @(x,y) polyval(p, [x(:), y(:)]);
% evaluate autonomous function
ZxAuto = reshape(fAuto(X,Y), N+1, []);
% plot results
figure(2)
clf
subplot(2,2,1)
contourf(X,Y,ZxAna)
title('F_x analytic at collocation points' )
hold on
plot(X(:),Y(:),'ro')
subplot(2,2,2)
contourf(X,Y,ZxNum)
title('F_x numeric at collocation points' )
subplot(2,2,3)
contourf(X,Y,ZxAuto)
title('F_x autonomous at collocation points' )
subplot(2,2,4)
contourf(X2,Y2,ZxAna2)
title('F_x analytic high resolution' )
hold on
plot(X(:),Y(:),'ro')
Attached below are the documentation links that you may find helpful:
- Polynomial curve fitting - MATLAB polyfit (mathworks.com)
- Fit curve or surface to data - MATLAB fit (mathworks.com) (Alternative)
Hope this helps!
Karan Singh Khati