Let's say that I want to solve a system of N
equations with N
unknown variables. Assume the equation is of the following general form (I have simplified it greatly, and we can pretend each line is equal to zero).
x1 - const(1)
x2 - const(2)
x3 - const(3)
...
xN - const(N)
where x1
, x2
, ..., xN
are my variables, and const
is a vector of length N
of constants determined earlier in the code. I do not know in advance (i.e. cannot hard-code) how many equations and variables there are, but I still wish to write and solve the system in a general way.
In MATLAB, my current solution is to do the following, where n_vars
is the number of variables, which my program determines earlier on.
sym_vars = sym('x',[1 n_vars]);
for i = 1:n_vars
eqn(i) = sym_vars(i)-const(i);
end
This builds the system of equations. eqn
, that I showed above. All of the numerical solvers (e.g. fsolve
, lsqnonlin
, ode45
) that I plan to use require the system of equations to be defined as a function handle or as a separate function entirely. I can convert the symbolic expression to a function handle via matlabFunction
or, if dealing with ODEs, via odeFunction
to address this.
However, there are two main issues with this approach that I want to resolve. The first is that I do not want to have to make symbolic variables and rely on the symbolic toolbox if I am only performing numerical computations. The second is that if I am solving ODEs, the variables actually have to be x1(t)
, x2(t)
, x3(t)
, ..., xN(t)
for odeFunction
to work properly. However, using the same logic as my sym
approach above to make these variables in a general way leads to a warning because character vectors that aren't valid variable names will not be allowed in future releases.
How can I write a system of equations using function handles instead of symbolic variables (or an equivalent solution)? Surely there must be a way to write a system of equations without doing so manually.
fun = @(x) x-c;
. – TroyHaskinN
different variables, but yours only shows 1. – Argon@(x) [x(1)-c(1),x(2)-c(2),...]
– Argonx
andc
are vectors of the same length,f
will be a vector-valued function. That idea is the most powerful way to numerically simulate systems. Ifx = [x1;x2;x3;...]
andc = [c1;c2;c3;...]
, thenf1 = @(x) x-c
will give[x1-c1;x2-c2;x3-c3;...]
. – TroyHaskinc = [1,2,3,4]; eq=@(x) x-c; solve(eq,[0,0,0,0]);
it throws an error because it's expecting one initial condition, not 4 (so, isn't it one variable, not 4?) – Argon