在C编程中,如何在不限制从文本文件读取的矩阵尺寸的情况下执行矩阵乘法



我想乘以矩阵,但不限制从不同文本文件MatAsmall.txt MatBsmall.txt MatAlarge.txt MatBlarge.txt中实际读取的矩阵A和B的尺寸。在不同的文本文件中有小矩阵,甚至有大矩阵。我想创建一个程序来读取任何维度的文件,然后将维度存储在一个变量中,这将有助于进一步进行矩阵乘法、多线程和动态内存分配。所有使用的矩阵都是2d。我该怎么做?

假设您的文件看起来像:

5 5
-9 8 -8 -3 10 
8 -10 10 -8 -4 
-2 -8 8 10 8 
4 3 5 -7 -7 
-5 4 -3 7 3 

其中5和5是后来定义的矩阵的维度,您可以使用这样的函数来读取它们:

struct matrix_t {
int **ptr;
int width;
int height;
};
struct matrix_t* matrix_create_struct(int width, int height) {
struct matrix_t *matrix = (struct matrix_t *) malloc(sizeof(struct matrix_t));
matrix->ptr = (int **) malloc(height * sizeof(int *));
for (int i = 0; i < height; i++) {
*(matrix->ptr + i) = (int *) malloc(width * sizeof(int));
}
matrix->width = width;
matrix->height = height;
return matrix;
}
struct matrix_t *matrix_load_from_file(const char *filename) {
FILE* fptr = fopen(filename, "rt");
int width, height;
fscanf(fptr, "%d", &width);
fscanf(fptr, "%d", &height);
struct matrix_t *matrix = matrix_create_struct(width, height);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
fscanf(fptr, "%d", (*(matrix->ptr + i) + j));
}
}
fclose(fptr);
return matrix;
}

这里我使用的是动态分配,因为正如你所说,我们不知道矩阵的维度是多少

为了将它们相乘:

struct matrix_t* matrix_multiply(const struct matrix_t *m1, const struct matrix_t *m2) {
if (m1->width != m2->height)
return NULL;
struct matrix_t *new_matrix = matrix_create_struct(m2->width, m1->height);
for (int i = 0; i < m1->height; i++) {
for (int j = 0; j < m2->width; j++) {
int res = 0;
for (int k = 0, l = 0; k < m1->width && l < m2->height; k++, l++)
res += *(*(m1->ptr + i) + k) * *(*(m2->ptr + l) + j);
*(*(new_matrix->ptr + i) + j) = res;
}
}
return new_matrix;
}

我在这里使用我在这里查找的数学:https://www.mathsisfun.com/algebra/matrix-multiplying.html.如果以下情况不正确,我将返回NULL:

第一个矩阵的列数必须等于第二个矩阵的行数。

请注意我有多乐观…如果每个fopen和malloc都没有返回NULL,就应该检查它,如果你不信任文件创建者,也要小心fscanfs。

我用这样的代码来测试我的代码:

void display_matrix(const struct matrix_t * matrix) {
for (int i = 0; i < matrix->height; i++) {
for (int j = 0; j < matrix->width; j++) {
printf("%d ", *(*(matrix->ptr + i) + j));
}
printf("n");
}
}
int main() {
struct matrix_t * m1 = matrix_load_from_file("test.txt");
struct matrix_t * m2 = matrix_load_from_file("test.txt");
struct matrix_t * m3 = matrix_multiply(m1, m2);
display_matrix(m3);
return 0;
}

并在此处检查结果:https://matrixcalc.org/.一切似乎都很好,但如果有问题或疑虑,请随时询问。

最新更新