Nonlinear curve fitting with summation function
조회 수: 12 (최근 30일)
이전 댓글 표시
I have the following data (Rt vs Sm) that I would like to fit with the following equation:

where ri=r0+i*(Ss+Sm), r0=30. In the fitting, Rs, Rm and LT are fitting parameters with initial guesses [100, 0.2, 0.2].
Please excuse the poor coding as I am new to MATLAB and have been using ChatGPT to help. I have the following code but it returned multiple errors and a few fixes doesn't seem to help. I am attaching the data file. Thank you in advance!
% Load data from Excel file
data = readtable('results.xlsx');
% Designate first column as Sm and second column as Rt
Sm = data(:,1).Variables;
Rt = data(:,2).Variables;
% Define fitting function
ri = 30+(0:9).*(10+Sm);
rj = (1:9).*(10+Sm);
fun = @(x,Sm) ((x(1))/(2*pi))*sum((log((ri+Sm)./ri))+((x(2))*((1./ri)+(1./(ri+Sm)))))+(x(3))/(2*pi)*(sum(log((rj-(x(2)))./(ri-10+(x(2))))));
% Set initial guess for fitting parameters
x0 = [100, 0.2, 0.2];
% Perform nonlinear curve fitting
x = lsqcurvefit(fun,x0,Sm,Rt);
% Calculate fitted values
Rt_fit = fun(x,Sm);
% Calculate R-square value
Rsq = 1 - sum((Rt - Rt_fit).^2)/sum((Rt - mean(Rt)).^2);
% Plot data and fitted curve
figure;
plot(Sm,Rt,'o',Sm,Rt_fit);
legend('Data','Fitted Curve');
xlabel('Sm');
ylabel('Rt');
댓글 수: 0
채택된 답변
Torsten
2023년 3월 2일
편집: Torsten
2023년 3월 2일
Check again whether fun is correctly defined.
I changed ri to rj in the last log expression.
% Load data from Excel file
data = readtable('results.xlsx');
% Designate first column as Sm and second column as Rt
Sm = data(:,1).Variables;
Rt = data(:,2).Variables;
% Define fitting function
ri = 30+(1:9).*(10+Sm);
rj = (1:9).*(10+Sm);
fun = @(x,Sm) x(1)/(2*pi)*sum(log((ri+Sm)./ri)+x(2)*(1./ri+1./(ri+Sm)),2)+x(3)/(2*pi)*sum(log((rj-x(2))./(rj-10+x(2))),2);
% Set initial guess for fitting parameters
x0 = [100, 0.2, 0.2];
% Perform nonlinear curve fitting
x = lsqcurvefit(fun,x0,Sm,Rt);
% Calculate fitted values
Rt_fit = fun(x,Sm);
% Calculate R-square value
Rsq = 1 - sum((Rt - Rt_fit).^2)/sum((Rt - mean(Rt)).^2);
% Plot data and fitted curve
figure;
plot(Sm,Rt,'o',Sm,Rt_fit);
legend('Data','Fitted Curve');
xlabel('Sm');
ylabel('Rt');
댓글 수: 3
Torsten
2023년 3월 2일
편집: Torsten
2023년 3월 2일
While I tested your code, I changed
ri = 30+(0:9).*(10+Sm);
to
ri = 30+(1:9).*(10+Sm);
You should correct this in the above code since you want to sum from 0 to 9 in the first sum.
Concerning your question:
The expressions
log((ri+Sm)./ri)+x(2)*(1./ri+1./(ri+Sm))
and
log((rj-x(2))./(rj-10+x(2)))
are matrices of size (number of elements of Sm) x (number of elements of ri resp. rj).
To compute the sums over the ri resp rj, it's necessary to sum the columns of this matrix. That's what the "2" stands for.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File 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!
