Solving set of equations containing array/matrix variables
mamuniut09 opened this issue · comments
Hello all,
I am wondering how to solve linear and nonlinear equations containing array/matrix variables using NLsolve. For example, if
a=[1 2 3; 4 5 6; 7 8 9]; b=[1; 2; 3];
ax+by+b=0........(1)
y-b=0.........(2)
how can I solve for vector x and y?
Also, how can I extract only the solution points (zeros) from the nlsolve results?
The example given in https://github.com/JuliaNLSolvers/NLsolve.jl is for scalar variables. It would be highly appreciated if anyone could help me out.
Do you mean how to solve for a vector x
and a vector y
?
It looks like a
and b
are simply parameters of the equation you are solving, in which case you can wrap them in a closure, and extract the two unknowns x
and y
from pieces of the variables. e.g. if x
and y
both are unknown vectors with length m
, then from NLsolve's perspective you have a single unknown vector X = [x; y]
of length 2m, and 2m equations F
.
For example:
function solvemyproblem(A, b, xinit, yinit)
m = length(xinit)
@views function f!(F::AbstractVector, X::AbstractVector)
x, y = X[1:m], X[m+1:end]
F[1:m] = A*x + y + b
F[m+1:end] = y - b
end
X = nlsolve!(f, [xinit; yinit])
return X[1:m], X[m+1:end] # final x, y
end
The above code allocates some temporary arrays for the vector operations. You could avoid these with code that uses in-place dot-broadcasting plus the in-place mul!
routine (from the LinearAlgebra
package) for the matrix-vector product:
mul!(F[1:m], A, x)
@. F[1:m] += y + b
@. F[m+1:end] = y - b
for example.