how to find the best order for a polynomial fitting in matlab

To find the best order for polynomial fitting in Matlab, we can use the polyfit function along with cross-validation to determine the best fit. The basic idea is to fit the polynomials of different orders to the data and select the order that provides the best fit based on some metric.

Here's an example implementation:

main.m
% Load dataset
load('mydata.mat')

% Split data into training and test sets
N = length(y);
idx = randperm(N);
idx_train = idx(1:floor(0.8*N));
idx_test = idx(floor(0.8*N)+1:end);

x_train = x(idx_train);
y_train = y(idx_train);
x_test = x(idx_test);
y_test = y(idx_test);

% Maximum order to consider
max_order = 10;

% Initialize arrays to store error metrics
train_err = zeros(max_order, 1);
test_err = zeros(max_order, 1);

% Loop over orders and fit polynomial
for i=1:max_order
   p = polyfit(x_train, y_train, i);
   y_train_fit = polyval(p, x_train);
   y_test_fit = polyval(p, x_test);
   
   % Compute error metrics for training and test sets
   train_err(i) = mean((y_train - y_train_fit).^2);
   test_err(i) = mean((y_test - y_test_fit).^2);
end

% Plot error metrics
figure
plot(1:max_order, train_err, 'bo-', 'LineWidth', 2)
hold on
plot(1:max_order, test_err, 'ro-', 'LineWidth', 2)
xlabel('Polynomial order')
ylabel('Error')
legend('Training set', 'Test set')
975 chars
41 lines

In this example, we first load the data from a file 'mydata.mat' and split it into 80% training set and 20% test set. We then loop over different orders (up to a maximum order of 10) and fit the polynomial using polyfit. For each order, we compute the mean squared error for both the training and test sets. Finally, we plot the error curves as a function of order and select the order that minimizes the test error.

Note that this is just one possible approach to order selection for polynomial fitting, and there are many other methods that could be used depending on the specific problem at hand.

gistlibby LogSnag