MATLAB: How to solve a system of 9 linear equations efficiently? (long computation time)

efficiencylong computation timeMATLABmatrix multiplicationsolvesymbolicsymbolic equationsystem of linear equations

I got a system of 9 linear equations which I received from a matrix multiplication. I want to solve this system efficiently for all 9 variables, altough I got some more symbolic variables in each equation. I was thinking of using a loop to solve this problem, but since I'm a newbie in Matlab, I'm not quite sure which method works best or how to solve this problem in an elegant way.
%% definitions
syms WC WP; % parameters

syms D1; %variable
syms G1 G2; % parameters
%h = 1.0545717*10^(-34);
h=1;
% variables
syms a1 a2 a3;
syms b1 b2 b3;
syms c1 c2 c3;
% matrices used
H=-h*0.5*[0 0 WP;
0 2*D1 WC;
WP WC 2*D1];
R=[a1 a2 a3;
b1 b2 b3;
c1 c2 c3];
B=[G1*c3 0 -0.5*a3*(G1 + G2);
0 G2*c3 -0.5*b3*(G1 + G2);
-0.5*c1*(G1 + G2) -0.5*c2*(G1 + G2) -c3*(G1 + G2)];
%% calculation
dtR = -1i/h*(H*R - R*H)+B == 0;
% extracting "equations" from the matrix result dtR and asigning a variable/equation
eqn1 = dtR(1,1);
eqn2 = dtR(1,2);
eqn3 = dtR(1,3); % <---- this should be doable in a loop?
eqn4 = dtR(2,1);
eqn5 = dtR(2,2);
eqn6 = dtR(2,3);
eqn7 = dtR(3,1);
eqn8 = dtR(3,2);
eqn9 = dtR(3,3);
eqns = [eqn1,eqn2,eqn3,eqn4,eqn5,eqn6,eqn7,eqn8,eqn9];
S = solve(eqns, [a1 a2 a3 b1 b2 b3 c1 c2 c3], 'ReturnConditions', true); % <--- this takes very long to compute
S.c1,
S.conditions,
S.parameters,
So the equations I get are a bit mixed up, but that shouldn't matter for solving this system of linear equations. However Matlab takes a really long time to compute this, so I hope someone has a tip or advice how I can solve this problem in a more efficient way.

Best Answer

  • The fastest way to solve a system of symbolic linear equations that is not fairly sparse, is to build
    M = sym('M', [rows, columns])
    S = M\B;
    S = subs(S, M, 1i/h*(H*R - R*H))
    Notice the sign changes. You had -expression+B=0 which is -expression=-B which is expression=B
    What you are doing here is solving with the simplest possible matrix, which gives you the pattern of the results. Then substitute in the actual values for the template values.
    Note: the special case of 2x2 can be executed slightly more efficiently with hand coding.