MATLAB Answers

Lsqnonlin to determine coefficient

9 views (last 30 days)
Anand Rathnam
Anand Rathnam on 7 Jun 2021
Edited: Matt J on 7 Jun 2021
I am looking to fit data to a complex equation using lsqnonlin solver. I am not sure where I am going wrong. I keep getting a response "not enough input arguments"
% Approach
% 1. Creating the following function named fit_simp.m which uses the time and Ar data(Ar = At/Ainf).
% 2. time and Ar are passed into lsqnonlin as input arguments.
% 3. Use the time and n data to calculate values values (Ar) the diffusion equation, and subtract the original Ar data from this.
% 4. The result will be the difference between the experimental data and the calculated values.
% 5. The lsqnonlin function will minimize the sum of the squares of the differences.
% 6. Condensation of the diffusion equation:
% a=0.0008;
% n1 = 2.43;
% n2= 1.4;
% Lambda = 950;
% theta = 45;
% gama = (2*n1*pi*sqrt ((sin(theta))^2-(n2/n1)^2))/(Lambda)
% Above entered in: 1-(8*gama/pi*(1-exp(-2*gama*a)))*((exp(-D*(2*n+1)^2*pi^2*t/4*a^2))*((-1)^n*2*gama +(((2*n+1)*pi)/(2*a))*exp(-2*gama*a))/((2*n+1)*((4*gama^2)+((2*n+1)*pi/2*a)^2)));
function diff = fit_simp(x,~,~) % This function is called by lsqnonlin.
% x is a vector which contains the coefficient of the equation.
% time and Ar are the option data sets that are passed to lsqnonlin
% Defining the data sets that you are trying to fit the function to.
Ar = [0.3 0.2 0.28 0.318 0.421 0.492 0.572 0.55 0.63 0.61 0.73 0.8 0.81 0.84 0.93 0.91]';
l = length(Ar);
t = [0:l-1]';
title('Data points')
% D is the coefficient we are looking to determine
n1 = 2.43;
Lambda = 950;
theta = 45;
d= x(1);
gama = (2*n1*3.14*sqrt ((sin(theta))^2-(n2/n1)^2))/(Lambda);
for t = 1:time
for n=0:time
r = 1-((8*gama/pi)*(1-exp(-2*gama*a)))*((exp(-d.*(2*n+1)^2*pi^2*t/4*a^2))*((-1)^n*2*gama +(((2*n+1)*pi)/(2*a))*exp(-2*gama*a))/((2*n+1)*((4*gama^2)+((2*n+1)*pi/2*a)^2)));
result(t) = r;
diff = result - Ar;
% Initialize the coefficients of the function.
% Calculate the new coefficients using LSQNONLIN.
% Plot the original and experimental data.
for t = 1:time
for n=0:time
Ar_new = 1-(8*gama/pi*(1-exp(-2*gama*a)))*((exp(-x(1).*(2*n+1)^2*pi^2*t/4*a^2))*((-1)^n*2*gama +(((2*n+1)*pi)/(2*a))*exp(-2*gama*a))/((2*n+1)*((4*gama^2)+((2*n+1)*pi/2*a)^2)))
Matt J
Matt J on 7 Jun 2021
@Anand Rathnam Note that your loop
for n=0:time
r = 1-((8*gama/pi)*...
is not doing anything except repeatedly over-writing r. It is not updating r in any way. You have a similar loop later in your posted code with the same problem.

Sign in to comment.

Answers (0)


Community Treasure Hunt

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

Start Hunting!