MATLAB: Backslash “\” operator is slow for symbolic matrices with diagonal numeric matrices

Symbolic Math Toolbox

Why is using the backslash "\" operator with a diagonal numeric matrix and a symbolic matrix slow?
In the following example we want to solve A*x = B. A is a diagonal numeric matrix and B is a symbolic matrix. Note that using inv(A)*B is much faster than A\B even though mathematically these statements are identical:
%Setup. A is type double, B is symbolic
syms x y z
I = eye(3);
B = [x;y;z];
B = B.^2 - 3;
%%Test A\B
tic
for i = 1:100
A = I*i;
A\B;
end
toc
%%Test inv(A)*B
tic
for i = 1:100
A = I*i;
inv(A)*B;
end
toc

Best Answer

Notice from the example above that if we have a diagonal double matrix "A" and a symbolic matrix "B" then solving "A*x=B" takes longer if using "A\B" rather than "inv(A)*B". Though mathematically these two expressions are the same, the algorithms used to solve each is different. Because "A" is a double matrix and "B" is a symbolic matrix, using "inv(A)*B" first runs the "inv" function for doubles and then uses the "mtimes" function from the Symbolic Toolbox. However, when you use "A\B", the "mldivide" function from the symbolic toolbox is used which uses a linear solver to solve A*x = B.
As for exactly what causes the difference between these two algorithms, the symbolic linear solver can sometimes encounter a phenomenon known as "expression swell" where the size of numbers and expressions involved in the calculation grow dramatically as the calculation progresses. This is what causes the computation to take much longer. Expression swell can occur in exact computation, like that used in the Symbolic Toolbox, but not in floating-point computation like that used for double datatypes. It is likely that the diagonal nature of the double matrix leads to this issue.
To avoid this problem, use "inv(A)*B" rather than "A\B" when "A" is a diagonal double matrix and "B" is symbolic.