MATLAB: Using fsolve to solve a set of equations with different constants every time

fsolve

Hi guys, so I have used fsolve to sucessful solve the following four simultaneous non linear equations:
F(1)=x(1)*(i*(w1-d1)+k1)-g*x(3)*x(2)-sqrt(2*k1in)*alpha1in;
F(2)=x(2)*(-i*(w1-d1)+k1)-conj(g)*x(4)*x(1)-sqrt(2*k1in)*conj(alpha1in);
F(3)=x(3)*(i*(w3-d3)+k3)+(g/2)*x(1)^2-sqrt(2*k3in)*alpha3in
F(4)=x(4)*(i*(w3-d3)+k3)+(g/2)*x(2)^2-sqrt(2*k3in)*alpha3in
This is solving for x(i) in the way I want it to. The next step that I cannot seem to make work is that I want to find x(i) for multiple different w1 values. and record each x(i). I know how to record the x(i) for each different w1 if I can get there. I just don't know how to change w1 without changing it manually and recording the x(i). I want to do this for about 1000 w1 values so manually changing is not a great option. Any help would be greatly appreciated!

Best Answer

Hi,
make a loop to vary w1 and pass it to fsolve by using one of the options in passing extra parameters.
An (incomplete) example would perhaps lok like this:
function x_all = main()
%Some code
d1 = 1;
k1 = 2;
g = 9.81;
w3 = 5;
k1in= 5;
alpha1in=10;
alpha3in=10;
x0 = zeros(1,4);
% Values for w1
w1_pool = 1:0.1:10;
% Preallocate result matrix
x_all = zeros(numel(w1_pool,numel(x0)));
% switch dispay off
options = optimoptions('fsolve','Display','off');
% Call fsolve in a loop
for k = 1 : numel(w1_pool)
w1 = w1_pool(k);
x_all(k,:) = fsolve(obj_fun,x0,options);
end
function F = obj_fun(x)
F(1)=x(1)*(1i*(w1-d1)+k1)-g*x(3)*x(2)-sqrt(2*k1in)*alpha1in;
F(2)=x(2)*(-1i*(w1-d1)+k1)-conj(g)*x(4)*x(1)-sqrt(2*k1in)*conj(alpha1in);
F(3)=x(3)*(1i*(w3-d3)+k3)+(g/2)*x(1)^2-sqrt(2*k3in)*alpha3in;
F(4)=x(4)*(1i*(w3-d3)+k3)+(g/2)*x(2)^2-sqrt(2*k3in)*alpha3in;
end
end
Save this function as .m-file named the function Name(main.m in this example). Obtain the result by calling the function like this
result = main
Best regards
Stephan