3D matrix multiplication In C
In C, we can use a 3-dimensional array to represent a 3D matrix, and then use nested loops to perform matrix multiplication.
Here’s an example of how we might do this:
#include <stdio.h>
void printMatrix(int m, int n, int o, int mat[m][n][o]) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < o; k++)
printf("%d ", mat[i][j][k]);
printf("\n");
}
printf("\n");
}
}
void matrixMultiplication(int m, int n, int o, int mat1[m][n][o], int mat2[m][n][o], int result[m][n][o]) {
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < o; k++)
result[i][j][k] = mat1[i][j][k] * mat2[i][j][k];
}
int main() {
int mat1[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
int mat2[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
int result[2][3][4];
matrixMultiplication(2, 3, 4, mat1, mat2, result);
printMatrix(2, 3, 4, result);
return 0;
}
In this example, we’ve defined two 3D matrices called mat1
and mat2
, with dimensions 2x3x4, and a third matrix result
with the same dimensions. The matrixMultiplication
function multiplies the two matrices element-wise, and the printMatrix
function is used to print the contents of the resulting matrix.
As we can see, 3D matrix multiplication is similar to 2D matrix multiplication, only with an additional nested loop to account for the third dimension. It’s important to note that this is not the classical matrix multiplication which is defined as dot product of matrices
It’s important to note that 3D matrix multiplication is not always used in regular use cases and this kind of operation could be used for specific tasks in fields such as image processing, physics simulation and others where 3D information is a must.
It is also worth noting that in case of doing a classical matrix multiplication with 3D matrices, the dimensions should match, such that the resulting matrix dimensions are the same as the dimensions of the first matrix.
Leave a Comment