How to fit curve using for loop?

15 次查看(过去 30 天)
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

采纳的回答

Mathieu NOE
Mathieu NOE 2021-10-4
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 个评论
AS
AS 2021-10-22
I want creat the matrix c from kmin to kmax.like c(2,5,1)....c(3,5,2).....c(20,5,19)....
But, using this code it is giving the final value of kmax with varying 1: 19.
So, how it will be solved. knidly, suggest me to resolve it. Thank you.
kmin=2;
kmax=20;
p=randperm(size(data,1)); % data is 3375 by 5
% generate initial centre
for i=kmin:kmax
for i1=1:5
for i2=1:19
c(i,:,i2)=(data(p(i),:));
end
end
end
Mathieu NOE
Mathieu NOE 2021-10-25
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),:));

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by