Fitting equation in matlab
Afficher commentaires plus anciens
I have an equation of the form y= a0+a1log(x)+ a2log(1/x)
I want to use polyfit but I don't know how to fix the degree of the polynomial in this case. Can anyone help me please?
Réponse acceptée
Plus de réponses (2)
Walter Roberson
le 16 Août 2013
0 votes
Any fixed degree that you use will result in a polynomial that tends to be infinitely wrong as x tends to infinity.
1 commentaire
sisay
le 16 Août 2013
Image Analyst
le 16 Août 2013
sisay, try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 24;
% Construct x.
x = linspace(.01, 40, 50);
a0 = 1;
a1 = 2;
a2 = 3;
% Create the perfect equation.
y = a0 + a1 * log(x)+ a2 * log(1./x);
subplot(3,1,1);
plot(x, y, 'b.-');
title('Noise-free signal', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Add some noise to make a noisy signal that we will fit.
yNoisy = y + 1.5 * rand(1, length(y));
subplot(3,1,2);
plot(x, yNoisy, 'b.-');
title('Noisy signal', 'FontSize', fontSize);
% Now get the fit
% y = a0 + a1 * log(x) - a2 * log(x)
% y = a0 + (a1 - a2) * log(x)
% y = (a1 - a2) * log(x) + a0
% Let newX = log(x), and (a1-a2) = coeffs(1), then
% y = coefficients(1) * newX + coefficients(2)
% so now we can use polyfit to fit a line.
newX = log(x);
coefficients = polyfit(newX, yNoisy, 1);
% Now get the fitted values
a0 = coefficients(2);
a1 = coefficients(1);
a2 = 0; % Might as well be 0 as any other value.
yFitted = a0 + a1 * log(x)+ a2 * log(1./x);
% and plot them
subplot(3,1,3);
plot(x, yNoisy, 'b.');
hold on;
plot(x, yFitted, 'r-', 'LineWidth', 3);
title('Fitted signal', 'FontSize', fontSize);
legend('Noisy data', 'Fitted signal');

Catégories
En savoir plus sur Polynomials dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!