Curve fitting in a for loop?

1 view (last 30 days)
Kelly McGuire
Kelly McGuire on 21 Feb 2019
Answered: Dev on 26 Mar 2025
I haven't tried this before, but I would like to run the code below in a for loop and have all of the data points and fitted curves plotted on the same plot. My data is in matrix form. I have 5 columns with concentrations (Concentration excel file), which should be xdata. There is also a average mortality excel file with 5 columns that have the average mortality, which should be ydata. Each cell in the aveMortality excel file lines up with a cell in the Concentration excel file. So, I would like the for loop to use the first Concentration column with the first column of the aveMortality matrix, and then the second columns, and so on. Then plot the curves as lines, and the xdata and ydata as large dots. Here is my code, and the excel files are attached:
xdata = Concentration;
ydata = aveMortality;
fun = @(x,xdata)(1./(1+(x(1)./xdata).^x(2)));
x0 = [180,1.6];
%x = lsqcurvefit(fun,x0,xdata,ydata,lb,ub)
opts = optimset('MaxFunEvals',1E+4, 'MaxIter',1E+4 );
x = fminsearch(@(x) norm(ydata - fun(x,xdata)), x0, opts)
figure
hold on
plot(xdata,ydata,'r.','markerszie', 30);
xlim([0 200]);
xlabel('Concentration','FontWeight','bold');
ylim([0 1]);
ylabel('Average Mortality','FontWeight','bold');
box off
y = 0:600;
plot(1./(1+(x(1)./y).^x(2)),'b-','markersize',3)
xlim([0 200])
ylim([0 1])

Answers (1)

Dev
Dev on 26 Mar 2025
In order to plot all the data points and curves plotted on the same plot using a ‘for’ loop, the code provided in the question above can be modified to include the ‘for’ loop as follows-
% Loop over each column of data
for i = 1:size(Concentration, 2)
% Extract current column data
xdata = Concentration(:, i);
ydata = aveMortality(:, i);
% Perform curve fitting
x = fminsearch(@(x) norm(ydata - fun(x, xdata)), x0, opts);
% Plot the data points
plot(xdata, ydata, 'o', 'MarkerSize', 8, 'DisplayName', sprintf('Data %d', i));
% Plot the fitted curve
x_fit = linspace(min(xdata), max(xdata), 100); % Generate x values for fitting
y_fit = fun(x, x_fit);
plot(x_fit, y_fit, '-', 'LineWidth', 2, 'DisplayName', sprintf('Fit %d', i));
end
For more information on the usage of ‘for’ loop, please refer to the documentation link below-
I have also attached the output plot obtained after using the above loop below, for your reference.
I hope this solves the purpose.

Community Treasure Hunt

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

Start Hunting!