How to use loops for inputting initial parameter values while solving system of non linear equations?

Hello everyone,
I have a system of 4 non-linear equations with 4 unknowns. I am able to solve the equations using the following code:
function solveeqs()
guess=[sqrt(0.5),0,0,sqrt(0.5)];
[result,fval,exit,output] = fsolve(@eqns,guess);
result
fval
eqns(guess)
output
end
function fcns = eqns(z)
a=z(1);
b=z(2);
c=z(3);
d=z(4);
fcns(1)=a^2+b^2-0.5023;
fcns(2)=c^2+d^2-0.4977;
fcns(3)=a*c+b*d+0.06585;
fcns(4)=b*c-a*d+0.49565;
end
But i need to solve the equation multiple times(1000) using different guess values and different function values. I need to create a loop (using lists) for doing so. Can you suggest a way to include loops for guess values and function values( fcns(1),fcns(2),fcns(3),fcns(4)) in above code? Thanks in advance.

8 Comments

Yeah i have values for all the guesses.
The values are in the form of lists.
a=[ ] (list of 1000 values)
b=[ ]
c=[ ]
d=[ ]
so the instance of guesses will be - guess = [a(1),b(1),c(1),d(1)]....................[a(i),b(i),c(i),d(i)]
Then just
for i = 1:1000
guess = [a(i) b(i) c(i) d(i)]];
[result,fval,exit,output] = fsolve(@eqns,guess);
end
Yeah thats's working, but i am facing another problem in the same code
m1=[sqrt(0.5),0.6,1]
m2=[0,0.1,0.3]
m3=[0,0.3,0.1]
m4=[sqrt(0.5),0.4,0.8]
for i=1:3;
guess=[m1(i),m2(i),m3(i),m4(i)];
[result,fval,exit,output] = fsolve(@eqns,guess);
result
fval
eqns(guess)
output
end
function fcns = eqns(z)
k1=[0.5023,0.5122,0.5087]
k2=[0.4977,0.4875,0.4955]
k3=[-0.06585,-0.06432,-0.06416]
k4=[-0.49565,-0.48732,-0.47654]
a=z(1);
b=z(2);
c=z(3);
d=z(4);
fcns(1)=a^2+b^2-k1(i);
fcns(2)=c^2+d^2-k2(i);
fcns(3)=a*c+b*d-k3(i);
fcns(4)=b*c-a*d-k4(i);
end
I need the iterations to be performed on not just the guess values, but also on the non-linear equations as i have different values of constants(k1(i),k2(i),k3(i),k4(i)) in fcns(1), ....fcns(4) as shown in the code above. But function @eqns is not taking 'i' as input while executing fsolve and giving an error like this. Can you please suggest me regarding this?? Thankyou.quesmatlab.PNG
  • But function @eqns is not taking 'i' as input
You can pass it:
[result,fval,exit,output] = fsolve(@(x)eqns(x,i),guess);
%% ...
function fcns = eqns(z,i)
Yeah its working. I have been stuck on this for an hour. Thank you very much.

Sign in to comment.

Answers (0)

Asked:

on 20 Nov 2019

Commented:

on 21 Nov 2019

Community Treasure Hunt

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

Start Hunting!