Strassen’s Matrix Multiplication is the divide and conquer approach to solve the matrix multiplication problems. The usual matrix multiplication method multiplies each row with each column to achieve the product matrix. The time complexity taken by this approach is O(n3), since it takes two loops to multiply. Strassens method was introduced to reduce the time complexity from O(n3) to O(nlog 7).
Naive Method
First, we will discuss Naive method and its complexity. Here, we are calculating Z=X Y. Using Naive method, two matrices (X and Y) can be multiplied if the order of these matrices are p q and q r and the resultant matrix will be of order p r. The following pseudocode describes the Naive multiplication −
Algorithm: Matrix-Multiplication (X, Y, Z)
for i = 1 to p do
for j = 1 to r do
Z[i,j] := 0
for k = 1 to q do
Z[i,j] := Z[i,j] + X[i,k] × Y[k,j]
Complexity
Here, we assume that integer operations take O(1) time. There are three for loops in this algorithm and one is nested in other. Hence, the algorithm takes O(n3) time to execute.
Strassens Matrix Multiplication Algorithm
In this context, using Strassens Matrix multiplication algorithm, the time consumption can be improved a little bit.
Strassens Matrix multiplication can be performed only on square matrices where n is a power of 2. Order of both of the matrices are n × n.
Divide X, Y and Z into four (n/2)×(n/2) matrices as represented below −
Z=[IKJL] X=[ACBD] and Y=[EGFH]
Using Strassens Algorithm compute the following −
M1:=(A+C)×(E+F)
M2:=(B+D)×(G+H)
M3:=(A−D)×(E+H)
M4:=A×(F−H)
M5:=(C+D)×(E)
M6:=(A+B)×(H)
M7:=D×(G−E)
Then,
I:=M2+M3−M6−M7
J:=M4+M6
K:=M5+M7
L:=M1−M3−M4−M5
Analysis
T(n)={c7xT(n2)+dxn2ifn=1otherwisewherecanddareconstants
Using this recurrence relation, we get T(n)=O(nlog7)
Hence, the complexity of Strassens matrix multiplication algorithm is O(nlog7).
Example
Let us look at the implementation of Strassen’s Matrix Multiplication in various programming languages: C, C++, Java, Python.
#include<stdio.h>intmain(){int z[2][2];int i, j;int m1, m2, m3, m4 , m5, m6, m7;int x[2][2]={{12,34},{22,10}};int y[2][2]={{3,4},{2,1}};printf("The first matrix is: ");for(i =0; i <2; i++){printf("\n");for(j =0; j <2; j++)printf("%d\t", x[i][j]);}printf("\nThe second matrix is: ");for(i =0; i <2; i++){printf("\n");for(j =0; j <2; j++)printf("%d\t", y[i][j]);}
m1=(x[0][0]+ x[1][1])*(y[0][0]+ y[1][1]);
m2=(x[1][0]+ x[1][1])* y[0][0];
m3= x[0][0]*(y[0][1]- y[1][1]);
m4= x[1][1]*(y[1][0]- y[0][0]);
m5=(x[0][0]+ x[0][1])* y[1][1];
m6=(x[1][0]- x[0][0])*(y[0][0]+y[0][1]);
m7=(x[0][1]- x[1][1])*(y[1][0]+y[1][1]);
z[0][0]= m1 + m4- m5 + m7;
z[0][1]= m3 + m5;
z[1][0]= m2 + m4;
z[1][1]= m1 - m2 + m3 + m6;printf("\nProduct achieved using Strassen's algorithm: ");for(i =0; i <2; i++){printf("\n");for(j =0; j <2; j++)printf("%d\t", z[i][j]);}return0;}
Output
The first matrix is: 12 34 22 10 The second matrix is: 3 4 2 1 Product achieved using Strassen's algorithm: 104 82 86 98
Leave a Reply