I am trying to solve nonlinear equations using fsolve command in Matlab. I have a main routine and I write a function in which I am defining the equations I want to solve.
Here is my main routine:
t = [338.9333333333,535.2,1217.4166666667,1797.3166666667,2082.9166666667,4557.0166666667,4690.2666666667,4717.5333333333,4981.3666666667,5346.9,5388.3166666667,5571.65,5619.65,6639.35,6719.35,7352.7666666667,7622.7666666667,7722.7666666667,7739.4333333333,7906.1,7909.7666666667,8502.7666666667,9852.7666666667,20571.0166666667,21368.6333333333,23948.6333333333,26789.6333333333,28598.6333333333,29828.6333333333,29859.6333333333,35469.6333333333,39938.6333333333,41186.6333333333,45956.6333333333,46378.6333333333,46496.6333333333,47493.6333333333,48958.6333333333,50228.6333333333,51716.6333333333,71876.6333333333];
n= length(t);
syms a b1 b2 amle b1mle b2mle
tau=zeros;
for tau=2:n-1
fun = @root2d;
x0=[0.0002,0.00004];
x=fsolve(fun,x0)
tau=tau+1;
end
and I have written a function separately and saved it as root2d.m as I could not insert the function inside the loop. Here is my function:
function F = root2d(x)
sum2=0;
for k=1:tau
sum2 = sum2+(2/x(1))-t(k);
k=k+1;
end
sum3=0;
for l=tau+1:n
sum3=sum3+(2/x(2))+t(tau)-t(l);
l=l+1;
end
F(1) = ((n*x(1)*(t(tau))^2)/(1-exp(x(1)*t(tau))+exp(x(1)*t(tau)-x(2)*(t(n)-t(tau)))*(1+x(2)*(t(n)-t(tau))))) + sum2;
F(2) = ((n*x(2)*(t(n)-t(tau))^2)/(1+x(2)*(t(n)-t(tau))+exp(x(2)*(t(n)-t(tau)))*((1+x(1)*t(tau))*exp(-x(1)*t(tau))-2))) + sum3;
end
However, this does not work until I define t, n, and tau inside the function. I tried defining the function as root2d(x,t,tau) but it does not work. Is there a way to pass the variables to the function and solve this?
You can add t, n and tau parameters to root2d function:
function F = root2d(x, t, n, tau)
...
end
Then in main loop you do
fun = @(x) root2d(x, t, n, tau);
Now fun is a function of one argument that call root2d with all needed arguments.