Can anyone teach me how to plot the line of best fit in this graph?
Matlab keeps gving me error message that polymial is not uniquie when i use polyfit() command

THx

% change working directory to data directory
cd C:\weatherdata
number_of_files=length(dir)-3;
for n=3:number_of_files 
s=load(['D',num2str(n),'.txt']);
% define y as height data
y = s(11,:);
% define x as temperature data
x = s(16,:);
% find the size of matrix s to define max of j
[rmax cmax]=size(s);
% input no. of columns of data programme will consider
for j= 1:cmax;
% eliminate data that has no height or temperature recorded
if x(1,j) ~= 99
if y(1,j) ~= 99
% convert height in feet to km and plot data points
plot(x(1,j),y(1,j)/3280.8399 ,'r+')
% command to prevent new plots from replacing old plots
P = polyfit(x(1,j),y(1,j),1);
Y = polyval(P,x(1,j));
hold on;
end
end
end
end
%label graph
xlabel('Temperature/°C')
ylabel('Height/km')
title('Graph of Height against Temperature','FontSize',12)
% insert grid
grid on

Matlab keeps gving me error message that polymial is not uniquie when i use polyfit() command

THx

Does the data include multiple points for the same x-value? For example, (2, 3); (2, 10); (2, 7); . . . ? If so, you may have to analyze one branch of the data at a time; I don't know how else you'd create a fit for data containing multiple y-values for a given x-value.

I don’t have my MATLAB manual handy at the moment, but it sounds like you are trying to do something like a least squares fit (the approximating line does NOT have to pass through all the data points, but the overall difference should be a minimum). And you know ahead of time what kind of relationship the data has: linear, quadratic, cubic, etc. Is this correct?

There are several programs beside MATLAB that can do that for you. And source code is available. In addition, here is a Javascript utility that does Linear Least-Squares Data-Fitting:

http://www.akiti.ca/LinLeastSqPoly4.html


On the other hand, if you want to create points such that a smooth line can then be drawn that DOES pass through existing data points, Cubic Spline Interpolation might be more appropriate. Again, many other programs can do this, and there is much source code available. And here is another Javascript utility, one that does Cubic Spline Interpolation:

http://www.akiti.ca/CubicSpline.html


Regards,


David

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.