现在的位置: 首页 > 综合 > 正文

两个N*N矩阵的乘法,矩阵由一维数组表示

2013年08月25日 ⁄ 综合 ⁄ 共 1145字 ⁄ 字号 评论关闭

#include <math.h>
#include <stdio.h>

/*This function will calculate two dimensional matrixes' product.
 * Please note, they are represented as one-dimensional arrays.
 * Note:
 * Only apply to line-storage matrix.
 */
void multiply(int result[], int a[], int b[], int n) {
    int i=0;
    int count=pow(n, 2);
    for (i=0; i<count; i++) {
        /* 1 = 4/3 */
        int row = i / n;
        int column = i % n;
        int k;
        result[i]=0;
        for (k=0; k < n; k++) {
            result[i] += a[row*n + k] * b[column + k*n];
        }
    }

}

/*This function will calculate two dimensional matrixes' product.
 * Please note, they are represented as one-dimensional arrays.
 * Note:
 * Only apply to column-storage matrix.
 */
void multiply2(int result[], int a[], int b[], int n) {
    int i=0;
    int count=pow(n, 2);
    for (i=0; i<count; i++) {
        /* 1 = 4/3 */
        int row = i % n;
        int column = i / n;
        int k;
        result[i]=0;
        for (k=0; k < n; k++) {
            result[i] += a[row + k*n] * b[column*n + k];
        }
    }

}

main() {
    int A[9]={1, 1, 1, 1, 1, 1, 1, 1, 1};
    int B[9]={1, 1, 1, 1, 1, 1, 1, 1, 1};
    int C[9];
    int i;
    multiply(&C, A, B, 3);
    for (i=0; i < 9; i++) {
        printf("%d ", C[i]);
    }

    printf("/n");

    multiply2(&C, A, B, 3);
    for (i=0; i < 9; i++) {
        printf("%d ", C[i]);
    }
    getch();
}

抱歉!评论已关闭.