我需要一个n*m矩阵相乘、相加、相减的矩阵运算的c语言代码,还有4*4矩阵和4*1矩阵相乘的c语言代码
时间: 2023-06-15 15:08:20 浏览: 112
以下是n*m矩阵相乘、相加、相减的C语言代码:
```c
#include <stdio.h>
void matrix_addition(int rows, int columns, int a[rows][columns], int b[rows][columns], int result[rows][columns]) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}
void matrix_subtraction(int rows, int columns, int a[rows][columns], int b[rows][columns], int result[rows][columns]) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
result[i][j] = a[i][j] - b[i][j];
}
}
}
void matrix_multiplication(int rows1, int columns1, int a[rows1][columns1], int rows2, int columns2, int b[rows2][columns2], int result[rows1][columns2]) {
if (columns1 != rows2) {
printf("Invalid matrix dimensions!\n");
return;
}
int i, j, k;
for (i = 0; i < rows1; i++) {
for (j = 0; j < columns2; j++) {
result[i][j] = 0;
for (k = 0; k < columns1; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main() {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[2][3] = {{7, 8, 9}, {10, 11, 12}};
int c[2][3], d[2][3], e[2][3];
matrix_addition(2, 3, a, b, c);
matrix_subtraction(2, 3, a, b, d);
matrix_multiplication(2, 3, a, 3, 2, b, e);
printf("Matrix A:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", b[i][j]);
}
printf("\n");
}
printf("Matrix A + B:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
printf("Matrix A - B:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", d[i][j]);
}
printf("\n");
}
printf("Matrix A * B:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", e[i][j]);
}
printf("\n");
}
return 0;
}
```
以下是4*4矩阵和4*1矩阵相乘的C语言代码:
```c
#include <stdio.h>
void matrix_multiplication(int rows1, int columns1, int a[rows1][columns1], int rows2, int columns2, int b[rows2][columns2], int result[rows1][columns2]) {
if (columns1 != rows2) {
printf("Invalid matrix dimensions!\n");
return;
}
int i, j, k;
for (i = 0; i < rows1; i++) {
for (j = 0; j < columns2; j++) {
result[i][j] = 0;
for (k = 0; k < columns1; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main() {
int a[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int b[4][1] = {{1}, {2}, {3}, {4}};
int c[4][1];
matrix_multiplication(4, 4, a, 4, 1, b, c);
printf("Matrix A:\n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for (int i = 0; i < 4; i++) {
printf("%d\n", b[i][0]);
}
printf("Matrix A * B:\n");
for (int i = 0; i < 4; i++) {
printf("%d\n", c[i][0]);
}
return 0;
}
```
阅读全文