簡體   English   中英

在 C 編程中,如何在不限制從文本文件讀取的矩陣維數的情況下執行矩陣乘法

[英]How can I perform Matrix Multiplication without restricting the dimensions of the matrices read from a text file in C programming

我想乘以矩陣但不限制實際從不同文本文件 MatAsmall.txt MatBsmall.txt MatAlarge.txt MatBlarge.txt 讀取的矩陣 A 和 B 的維度。 不同的文本文件中有小矩陣,甚至有大矩陣。 我想創建 1 個程序來讀取任何維度的文件,然后將維度存儲在一個變量中,這將有助於進一步進行矩陣乘法、多線程和動態 memory 分配。 所有使用的矩陣都是二維的。 我怎樣才能做到這一點?

如果您的文件類似於:

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 是后面定義的矩陣的維度,你可以使用這樣的 function 來讀取它們:

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/ 一切似乎都運行良好,但如有問題或疑問,請隨時提出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM