Here's a C implementation for performing in-place matrix multiplication of two 2D arrays. This implementation assumes that the matrices are compatible for multiplication (i.e., the number of columns in the first matrix is equal to the number of rows in the second matrix).
#include <stdio.h>
// Function to perform in-place matrix multiplication
void multiplyMatrices(int rowsA, int colsA, int colsB, int matrixA[rowsA][colsA], int matrixB[colsA][colsB]) {
// Create a temporary matrix to store the result
int temp[rowsA][colsB];
// Perform matrix multiplication and store the result in temp
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
temp[i][j] = 0;
for (int k = 0; k < colsA; k++) {
temp[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Copy the result back to matrixA (in-place multiplication)
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
matrixA[i][j] = temp[i][j];
}
}
}
int main() {
// Example matrices
int matrixA[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int matrixB[3][2] = {
{7, 8},
{9, 10},
{11, 12}
};
int rowsA = 2;
int colsA = 3;
int colsB = 2;
// Perform in-place matrix multiplication
multiplyMatrices(rowsA, colsA, colsB, matrixA, matrixB);
// Print the result
printf("Resultant Matrix:\n");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
printf("%d ", matrixA[i][j]);
}
printf("\n");
}
return 0;
}
Key improvements and explanations:
- In-place matrix multiplication: The function
multiplyMatrices performs the matrix multiplication and stores the result in the first matrix matrixA. This is done by using a temporary matrix temp to store the intermediate results and then copying the results back to matrixA.
- Matrix multiplication logic: The nested loops correctly perform the matrix multiplication by iterating over each element of the resulting matrix and computing the dot product of the corresponding row of
matrixA and column of matrixB.
- Parameter passing: The function
multiplyMatrices takes the dimensions of the matrices as parameters, which makes it more flexible and reusable.
- Memory management: The temporary matrix
temp is allocated on the stack, which is efficient and avoids the need for dynamic memory allocation.
How to compile and run:
-
Save: Save the code as a .c file (e.g., matrix_multiplication.c).
-
Compile: Open a terminal or command prompt and compile the code using a C compiler (like GCC):
gcc matrix_multiplication.c -o matrix_multiplication
-
Run: Execute the compiled program:
./matrix_multiplication
The program will print the resultant matrix after performing the in-place matrix multiplication.
Example Output:
Resultant Matrix:
58 64
139 154
This output corresponds to the matrix multiplication of the given example matrices.