Fitting equation in matlab
2 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Matt J
on 16 Aug 2013
Edited: Matt J
on 16 Aug 2013
Since log(1/x)=-log(x) your equation model has redundant terms. It is equivalent to
y = a0+(a1-a2)*log(x)
= A+B*log(x)
where a0 has been relabeled as A and B has replaced a1-a2.
You could fit A and B, I suppose, by doing
AB=polyfit(log(x),y,1);
A=AB(2);
B=AB(1);
18 Comments
Walter Roberson
on 16 Aug 2013
Your equation is underdetermined. There are an infinite number of (a1, a2) pairs that will work in your equation; everything along the ray starting from a2 = epsilon (epsilon being positive and arbitrarily close to zero) and up, with only the difference calculatable.
Unless, that is, you have additional information that can be used to constrain the two values.
More Answers (2)
Walter Roberson
on 16 Aug 2013
Any fixed degree that you use will result in a polynomial that tends to be infinitely wrong as x tends to infinity.
Image Analyst
on 16 Aug 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');
0 Comments
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!