Skip to content

Instantly share code, notes, and snippets.

Created February 10, 2013 16:59
Show Gist options
  • Save anonymous/1ef128bc3d378a988e69 to your computer and use it in GitHub Desktop.
Save anonymous/1ef128bc3d378a988e69 to your computer and use it in GitHub Desktop.
C++ Matrices
#include <iostream>
using namespace std;
const int n = 3; // Change this as needed for a new test.
typedef float SquareMatrixType[n][n];
void MatrixSum(int size, SquareMatrixType A, SquareMatrixType B, SquareMatrixType Result);
void Print(int size, SquareMatrixType M);
int main(void)
{
SquareMatrixType First = { {2.0, 1.0, 3.0},
{0.0, 4.0, -1.0},
{-2.0, 5.0, 1.0}
};
SquareMatrixType Second = { {1.0, 6.0, 0.0},
{-2.0, 4.0, -1.0},
{0.0, 3.0, 2.0}
};
SquareMatrixType Sum;
MatrixSum(n, First, Second, Sum);
cout << "First matrix:" << endl;
Print(n, First);
cout << endl << "Second matrix:" << endl;
Print(n, Second);
cout << endl << "Sum matrix:" << endl;
Print(n, Sum);
cout << endl;
return 0;
}
void MatrixSum(int size, SquareMatrixType A, SquareMatrixType B, SquareMatrixType Result)
{
int row, col;
for (row = 0; row < size; row++)
{
for (col = 0; col < size; col++)
Result[row][col] = A[row][col] + B[row][col];
}
}
void Print(int size, SquareMatrixType M)
{
int row, col;
for (row = 0; row < size; row++)
{
for (col = 0; col < size; col++)
cout << M[row][col] << " ";
cout << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment