How to implement matrix multiplication in C++

2 Answers

0 votes
#include <iostream>
#include <iomanip>
 
#define N 3
  
class calc {
  public:
    void print(int arr2d[][N]);
    int multiply(int a[][N], int b[][N], int i, int j);
};
 
void calc::print(int arr2d[][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            std::cout << std::setw(4) << arr2d[i][j];
        std::cout << "\n";
    }
}
 
int calc::multiply(int a[][N], int b[][N], int i, int j) {
    int sum = 0;
  
    for (int x = 0; x < N; x++)
        sum += a[i][x] * b[x][j];
      
    return sum;
}
  
int main()
{
    int a[N][N] = { { 1, 8, 5 },{ 6, 7, 1 },{ 8, 7, 6 } };
    int b[N][N] = { { 4, 8, 1 },{ 6, 5, 3 },{ 4, 6, 5 } };
    int c[N][N] = {{0}};
    calc clc;
  
    clc.print(a);
    std::cout << "\n";
    clc.print(b);
    std::cout << "\n";
  
    // c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
  
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            c[i][j] = clc.multiply(a, b, i, j);
    clc.print(c);
}
  
  
  
/*
run:
  
1   8   5
6   7   1
8   7   6
  
4   8   1
6   5   3
4   6   5
  
72  78  50
70  89  32
98 135  59
  
*/

 



answered Feb 28, 2016 by avibootz
edited 3 days ago by avibootz
0 votes
#include <iostream>
#include <iomanip>
 
#define N 3
  
class calc {
  public:
    void print(int arr2d[][N]);
    void multiple_matrix(int a[][N], int b[][N], int c[][N]);
};
 
void calc::print(int arr2d[][N]) {
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            std::cout << std::setw(4) << arr2d[i][j];
        std::cout << "\n";
    }
}
 
void calc::multiple_matrix(int a[][N], int b[][N], int c[][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < N; k++)
                c[i][j] = c[i][j] + a[i][k] * b[k][j];
        }
    }
}
  
int main()
{
    int a[N][N] = { { 1, 8, 5 },{ 6, 7, 1 },{ 8, 7, 6 } };
    int b[N][N] = { { 4, 8, 1 },{ 6, 5, 3 },{ 4, 6, 5 } };
    int c[N][N] = {{0}};
    calc clc;
  
    clc.print(a);
    std::cout << "\n";
    clc.print(b);
    std::cout << "\n";
  
    // c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
  
    clc.multiple_matrix(a, b, c);
  
    clc.print(c);
}

  
  
/*
run:
  
1   8   5
6   7   1
8   7   6
  
4   8   1
6   5   3
4   6   5
  
72  78  50
70  89  32
98 135  59
  
*/

 



answered Feb 28, 2016 by avibootz
edited 3 days ago by avibootz
...