ONLY DO WHAT ONLY YOU CAN DO

こけたら立ちなはれ 立ったら歩きなはれ

行列の積 (C++)

たとえば, 3行5列の行列と, 5行4列の行列との積は, 以下のように
3行4列の行列になる.
f:id:fornext1119:20140731221630p:plain
上記の場合,
f:id:fornext1119:20140731221755p:plain

#include <iostream>
using namespace std;

void multiply(double a[3][5], double b[5][4], double c[3][4]);

int main()
{
    cout << 'A' << endl; 
    double a[3][5] = {{11,12,13,14,15},{21,22,23,24,25},{31,32,33,34,35}}; 
    for (int i = 0;i<=2;i++)
    {
        for (int j = 0;j<=4;j++)
           cout << a[i][j] << '\t'; 
       cout << endl; 
    }
    
    cout << 'B' << endl; 
    double b[5][4] = {{11,12,13,14},{21,22,23,24},{31,32,33,34}, {41,42,43,44},{51,52,53,54}};
    for (int i = 0;i<=4;i++)
    {
        for (int j = 0;j<=3;j++)
           cout << b[i][j] << '\t'; 
       cout << endl; 
    }

    cout << 'C' << endl; 
    double c[3][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0}};
    multiply(a,b,c);
    for (int i = 0;i<=2;i++)
    {
        for (int j = 0;j<=3;j++)
           cout << c[i][j] << '\t'; 
       cout << endl; 
    }
   
    return 0;
}

void multiply(double a[3][5], double b[5][4], double c[3][4] )
{
    int i, j, k;
    double s;

    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 4; j++)
        {
            s = 0;
            for (k = 0; k < 5; k++)
                s += a[i][k] * b[k][j];
            c[i][j] = s;
        }
    }
}
A
11	12	13	14	15	
21	22	23	24	25	
31	32	33	34	35	
B
11	12	13	14	
21	22	23	24	
31	32	33	34	
41	42	43	44	
51	52	53	54	
C
2115	2180	2245	2310	
3665	3780	3895	4010	
5215	5380	5545	5710	
参考文献