# Solving system of equations

Hi. I’m interested in ‘nlsolve’ function for solving system of equations.

Let us consider simple example:
Eq.1: y=a+x
Eq.2: y=2x-1,
where a is a vector that it can take values 3 and 5.

I want to solve system of equations for each value of a.
For a=3, (x,y)=(4,7), and for a=5, (x,y)=(6,11).

I solve it in a loop:

using NLsolve

function f!(F, x, a)
F[1] =a+x[1]-x[2]
F[2] =2*x[1]-1-x[2]
end

K=zeros(2, length(a))
initial_x=[ 0.1; 0.2]

a=[3.0; 5.0]

for i=1:length(a)
res=nlsolve((F,x) -> f!(F, x, a[i]), initial_x)
K[:,i]=res.zero
end

Is there any smart way to avoid looping?

Also, I would appreciate if you can explain the helper function `n_ary`.
Thank you.

This is just a system of linear equations so there is no need for NLSolve. Assuming it is just a simple example, what is wrong with writing a loop?

1 Like

Welcome to the Julia community! I can’t help with your particular issue, but it might be worth taking a look at this thread about posting questions here in discourse. In particular, you can get the code formatted, making it a bit easier to read. Compare

function foo()
println(“this looks like normal text”)
end

To:

``````function bar()
println("oh, so much better!")
end
``````
2 Likes

If it’s just about avoiding this loop:

then I guess you could do

``````res = [nlsolve((F,x) -> f!(F, x, aᵢ), initial_x) for aᵢ in a]
K = [r.zero for r in res]
``````

But I’m not sure that’s an improvement over the loop? Loops in Julia are generally as fast as “vectorized” code, so in case you’re coming from Matlab/R or a similar environment where vectorization is the key to fast code you can stop worrying!

1 Like