113. Multiplying matrices via the Vector API
Let’s consider two matrices of 4x4 denoted as X
and Y
. Z=X*Y
is as follows:
Figure 5.10: Multiplying two matrices (X * Y = Z)
Multiplying X
with Y
means multiplying the first row from X
with the first column from Y
, the second row from X
with the second column from Y
, and so on. For instance, (1 x 3) + (2 x 7) + (5 x 5) + (4 x 5) = 3 + 14 + 25 + 20 = 62. Basically, we repeatedly apply FMA computation and fill up Z
with the results.
In this context, and based on the previous problem about computing FMA, we can produce the following code for multiplying X
with Y
:
private static final VectorSpecies<Float> VS
= FloatVector.SPECIES_PREFERRED;
public static float[] mulMatrix(
float[] x, float[] y, int size) {
final int upperBound = VS.loopBound(size);
float[] z = new float[size * size];
for (int i = 0; i < size; i++) {
for (int k = 0; k < size; k++) {
float elem = x[i * size + k]...