How to fit curve using for loop?
15 views (last 30 days)
Show older comments
I have a 15 number of signals with data point 64 in each. I want to use loop to fit all the signals with fittype 'gauss2' and plot all the curves with thier fitting. I have written like this but it is showing eroor. Kindly suggest me to resolve this. Thank you.
figure;
for i1=1:64
for j1=1:15
recon1_f(j1)=fit(t(i1),recon_amp2_1(:,j1),'gauss2');
h2{i}=plot(recon1_f(j1),t,recon_amp2_1(:,j1));
ylim([0 0.05]);
end
end
1 Comment
Accepted Answer
Mathieu NOE
on 4 Oct 2021
hello again
in the mean time I created this example (only 5 loops) on dummy data
you can easily expand and adapt it to your own needs
NB you only need one for loop and not two as in your code
hope it helps
clearvars
clc
% dummy data
x1 = [0:1:20];
y1 = [0,0.004,0.008,0.024,0.054,0.112,0.33,0.508,0.712,0.926,1,0.874,0.602,0.404,0.252,0.146,0.074,0.036,0.018,0.004,0];
for ci = 1:5
% modify x and y range (dummy data generation)
x = x1*ci;
y = y1*ci^2 + 0.1*rand(size(y1));
% curve fit using fminsearch
f = @(a,b,c,x) a.*exp(-(x-b).^2 / c.^2);
obj_fun = @(params) norm(f(params(1), params(2), params(3),x)-y);
sol = fminsearch(obj_fun, [max(y),max(x)/2,max(x)/6]);
a_sol = sol(1);
b_sol = sol(2);
c_sol = sol(3);
xx = linspace(min(x),max(x),300);
y_fit = f(a_sol, b_sol,c_sol, xx);
yy = interp1(x,y, xx);
Rsquared = my_Rsquared_coeff(yy,y_fit); % correlation coefficient
figure(ci)
plot(xx, y_fit, '-',x,y, 'r .', 'MarkerSize', 40)
title(['Gaussian Fit / R² = ' num2str(Rsquared) ], 'FontSize', 15)
ylabel('Intensity (arb. unit)', 'FontSize', 14)
xlabel('x(nm)', 'FontSize', 14)
eqn = " y = "+a_sol+ " * exp(-(x - " +b_sol+")² / (" +c_sol+ ")²";
legend(eqn)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Rsquared = my_Rsquared_coeff(data,data_fit)
% R2 correlation coefficient computation
% The total sum of squares
sum_of_squares = sum((data-mean(data)).^2);
% The sum of squares of residuals, also called the residual sum of squares:
sum_of_squares_of_residuals = sum((data-data_fit).^2);
% definition of the coefficient of correlation is
Rsquared = 1 - sum_of_squares_of_residuals/sum_of_squares;
end
20 Comments
Mathieu NOE
on 25 Oct 2021
hello
seems to me the index i1 is not usedin the line
c(i,:,i2)=(data(p(i),:));
so It should be
c(i,i1,i2)=(data(p(i),:));
More Answers (0)
See Also
Categories
Find more on Get Started with Curve Fitting Toolbox 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!