0
votes

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.

1
Well, for the case you presented, it's simply fun = @(x) x-c;.TroyHaskin
How so? There are N different variables, but yours only shows 1.Argon
I would want @(x) [x(1)-c(1),x(2)-c(2),...]Argon
If both x and c are vectors of the same length, f will be a vector-valued function. That idea is the most powerful way to numerically simulate systems. If x = [x1;x2;x3;...] and c = [c1;c2;c3;...], then f1 = @(x) x-c will give [x1-c1;x2-c2;x3-c3;...].TroyHaskin
When I do, for example: c = [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

1 Answers

0
votes

Use a vector function like

N=5;
const=1:5;
fsolve(@(x)x-const,zeros(1,N))

the result is:

1.0000    2.0000    3.0000    4.0000    5.0000