Matlab: Efficient and Inefficient Matrices Multipliers

The problem is only in the matrices A

, B

, C

and D

that n*n

and x

that are vectors of length n

, to find E = DCBAx

in the most effective way to use Matlab and least effective way.

The most obvious way to calculate E

is to simply increase their straightness.

Is this the most efficient way? What's the least efficient way?

+3


source to share


1 answer


Let's create dummy matrices and a 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);

      

We can then define some function descriptors for matrix products in which we force the order of 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 estimate of the runtime with the help timeit

shows that fun1

, fun2

and fun3

work almost the same, and fun4

- about 100 times faster. The reason for this behavior is that in the first three cases we need 3 matrix products and 1 matrix-vector product, and in the last - only 4 matrix-vector products. Interestingly, Matlab cannot recognize this simple optimization when evaluating fun1

.

+8


source







All Articles