Curve fit for multiple datasets

38 views (last 30 days)
RJohnson
RJohnson on 23 Nov 2015
Answered: Szu-Yu Lee on 8 Apr 2021
Hello,
I have a relatively easy question but since I'm new to Matlab I haven't been able to figure it out. I have two arrays; one of x values and one of y values. Both are arrays with 101 rows and 40 columns. The first column in the X1 array corresponds to the the x values for the first column of values in Y1. The second column in X1 to the second column in Y1; the third column in X1 to the third column in Y2 and so forth. I want to perform a polynomial curve fit on all 40 columns of data and have the resultant data (i.e. the new "fitted" Y values) available in the workspace. I can perform the fit for one curve with no problem. The code is below for the 20th column of data:
[curve1 gof1]=polyfit(X1(:,20),Y1(:,20),9);
Y2=polyval(curve1,X1(:,20));
%(optional plotting):
plot(X1(:,20),Y1(:,20),'*',X1(:,20),Y2,':');
If I want to fit all 40 columns, can I use a for-loop or is there something more elegant? Here is what I have tried; it works, but I'm open to suggestions for improvement.
for i=1:40;
[curve1 gof1]=polyfit(X1(:,i),Y1(:,i),9);
Y2(:,i)=polyval(curve1,X1(:,i));
end

Answers (2)

Image Analyst
Image Analyst on 24 Nov 2015
I'd call unique(X) to get all the unique x values, just in case they're different from one column to the next.
uniqueX = unique(X);
Then I'd call interp1() on each x,y pairing with the unique values of x. So now you have all the curves sampled at the same x locations. So then I'd just take the mean of all the interpolated y values to get the average at each x
meanY = mean(interpolatedY, 2);
Then do your curve fitting, whether it's via polyfit() or something fancier, on the curve with uniqueX and meanY. Others may have different ideas but it seems reasonable to me. It's worth a shot. Give it a try.
  4 Comments
Muzammilanwar Khan
Muzammilanwar Khan on 9 Jan 2021
Hello! I have many x-y data and I want to fit polynomial in all these data sets. So, if I have 'n' number of data set (x,y), can I get curves (n) for all these data sets. How can I write the code for the same?
Image Analyst
Image Analyst on 9 Jan 2021
Start a new discussion thread and attach your data and the order of the polynomial you want to fit.

Sign in to comment.


Szu-Yu Lee
Szu-Yu Lee on 8 Apr 2021
Hi, I guess you are trying to fit a large number of independent equations? MATLAB "fit" function do not support multiple independent curves fitting. I have created a function that takes in a 2D matrix, where each row is a curve to be fitted to some polynomial expression. The function does not use for-loop, so can work on large number of rows in a very short time.
https://www.mathworks.com/matlabcentral/fileexchange/90017-matrix-row-wise-polynomial-fit

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!