#include void multiplication(double **matOut, double **matA, int matARows, int matACols, double **matB, int matBRows, int matBCols); int main(){ double **matOut, **matA, **matB; int matOutRows, matOutCols; int matARows, matACols, matBRows, matBCols; int i, j; matARows = 4; matACols = 2; matBRows = 2; matBCols = 3; // メモリ確保 matOut = malloc(sizeof(double*) * matARows); matA = malloc(sizeof(double*) * matARows); matB = malloc(sizeof(double*) * matBRows); for(i = 0; i < matARows; ++i){ matOut[i] = malloc(sizeof(double) * matBCols); matA[i] = malloc(sizeof(double) * matACols); } for(i = 0; i < matBRows; ++i){ matB[i] = malloc(sizeof(double) * matBCols); } // データ初期化 for(i = 0; i < matARows; ++i){ for(j = 0; j < matACols; ++j){ matA[i][j] = i * matACols + j; } } for(i = 0; i < matBRows; ++i){ for(j = 0; j < matBCols; ++j){ matB[i][j] = 3.0; } } for(i = 0; i < matARows; ++i){ for(j = 0; j < matBCols; ++j){ matOut[i][j] = 0.0; } } // 初期状態確認 printf("matrixA initialized\n"); for(i = 0; i < matARows; ++i){ for(j = 0; j < matACols; ++j){ printf("%.3f ", matA[i][j]); } printf("\n"); } printf("matrixB initialized\n"); for(i = 0; i < matBRows; ++i){ for(j = 0; j < matBCols; ++j){ printf("%.3f ", matB[i][j]); } printf("\n"); } // 計算 multiplication(matOut, matA, matARows, matACols, matB, matBRows, matBCols); // 計算結果 printf("matrixOut\n"); for(i = 0; i < matARows; ++i){ for(j = 0; j < matBCols; ++j){ printf("%.3f ", matOut[i][j]); } printf("\n"); } // メモリ解放 for(i = 0; i < matARows; ++i){ free(matOut[i]); free(matA[i]); } for(i = 0; i < matBRows; ++i){ free(matB[i]); } free(matOut); free(matA); free(matB); return 0; } /* matOut : 計算結果 matA : 入力行列A matARows : 入力行列Aの行数 matACols : 入力行列Aの列数 matB : 入力行列B matBRows : 入力行列Bの行数 matBCols : 入力行列Bの列数 */ void multiplication(double **matOut, double **matA, int matARows, int matACols, double **matB, int matBRows, int matBCols){ int i, j, k; if( matACols != matBRows ){ printf("計算できません\n"); return; } for(i = 0; i < matARows; ++i){ for(j = 0; j < matBCols; ++j){ matOut[i][j] = 0.0; for(k = 0; k < matACols; ++k){ matOut[i][j] += matA[i][k] * matB[k][j]; } } } }