NoMan
NoMan

Reputation: 67

Solving the system of non-linear equations in MATLAB by fsolve

I have a code that produces a vector in MATLAB, for example the following is a three component vector (n=3):

a1_1 - sin((17*a1_1)/60 + a2_1/8 + a3_1/40 - 0.153233)
(15*a1_1)/16 + a2_1/4 + a3_1/32 - sin((17*a1_1)/60 + a2_1/8 + a3_1/40 - 0.0282326)
(3*a1_1)/4 + a2_1/2 + a3_1/8 - sin((17*a1_1)/60 + a2_1/8 + a3_1/40 + 0.846767)

as you can see each component is a non-linear equation. The three component of the vector forms a system of three non-linear equations having it's variables named as a1_1, a1_2and a1_3. I want to solve this system by fsolve.

How do I do that for arbitrary n?

Upvotes: 0

Views: 1399

Answers (2)

horchler
horchler

Reputation: 18484

To use fsolve, your function must accept a vector input and return a vector of the same size. In your case you can accomplish this with an anonymous function:

f = @(a)[a(1) - sin(17*a(1)/60 + a(2)/8 + a(3)/40 - 0.153233);...
         15*a(1)/16 + a(2)/4 + a(3)/32 - sin(17*a(1)/60 + a(2)/8 + a(3)/40 - 0.0282326);...
         3*a(1)/4 + a(2)/2 + a(3)/8 - sin(17*a(1)/60 + a(2)/8 + a(3)/40 + 0.846767)];
n = 3;
a0 = zeros(n,1); % Initial guess
opts = optimoptions('fsolve','Display','iter','TolFun',1e-8);
[a_sol,a_val,exitflag] = fsolve(f,a0,opts)

This returns

a_sol =

  -0.002818738864459
  -0.687953796565011
   9.488284986072076

Of course there may be more than one solution, especially for larger n. You can choose your initial guess to find the others. See the documentation for fsolve and optimoptions for further details on on specifying options.

Upvotes: 1

Peut22
Peut22

Reputation: 304

Did you try using the solve command ?

[y1,...,yN] = solve(eqns,vars) solves the system of equations eqns for the variables vars. The solutions are assigned to the variables y1,...,yN. If you do not specify the variables, solve uses symvar to find the variables to solve for. In this case, the number of variables that symvar finds is equal to the number of output arguments N.

Upvotes: 0

Related Questions