Let us create the dummy matrices and vector for this example.
n = 1000;
A = rand(n, n);
B = rand(n, n);
C = rand(n, n);
D = rand(n, n);
x = rand(n, 1);
Then we can define some function handles for the matrix products, in which we force the order of the operations
fun1 = @() D*C*B*A*x;
fun2 = @() (D*C*B*A)*x;
fun3 = @() (D*(C*(B*A)))*x;
fun4 = @() D*(C*(B*(A*x)));
A simple execution time evaluation with timeit
shows that fun1
, fun2
and fun3
perform nearly in the same way, while fun4
is about 100 times faster. The reason for this behavior is that in the first three cases we require 3 matrix products and 1 matrix-vector product, while in the last one only 4 matrix-vector products are performed. Interestingly Matlab is not able to recognize this simple optimization when it evaluates fun1
.