So a friend and I are in a linear algebra class this semester and hate doing matrix inverses and looked ahead and got the (assume A is a nxn matrix):
A^-1 = (1/(|A|)) * adj(A) But screw that so we wanted to write a program to do it for us! We kind of found this nifty pattern for finding the determinant of a matrix. Given: a 3x3 matrix, the determinant is simply:
|a b c|
|d e f| (a*e*i)+(b*f*g)+(c*d*h)
|g h i|
So after thinking a for a while we came up with this code.
The matrix im using to test is:
|1 2 3|
|4 5 6|
|7 8 9|
#include <iostream>
#include <vector>
usingnamespace std;
int main(){
int rows = 0;
int columns = 0;
cout << "Enter the rows of the matrix" << endl;
cin >> rows;
cout << "Enter the columns of the matrix" << endl;
cin >> columns;
vector<vector<int> > matrix((rows ), vector<int>(columns));
cout << "Enter the matrix in: a11, then a12, then a13, etc" << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
cin >> matrix [i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
cout << matrix [i][j] << " ";
}
cout << endl;
}
int r = 0;
int c = 0;
int diag1 = 1;
while(r < rows)
{
diag1 = diag1*(matrix[r][c]);
r++;
c++;
};
cout << "The first diagonal is: " << diag1 << endl;
int ro = 0;
int co = 1;
int diag2 = 1;
while(ro < rows)
{
diag2 = diag2*(matrix[ro][co]);
if (co == columns)
{co = 0;}
else {co++;}
ro++;
cout << "ro: " << ro << "co " << co << endl;
};
cout << "The second diagonal is: " << diag2 << " not working -___-" << endl;
int row = 0;
int col = 2;
int diag3 = 1;
while (row < rows)
{
diag3 = diag3*(matrix[row][col]);
if (col == columns)
{col = 0;}
else{col++;}
row++;
}
cout << "The third diagonal is: " << diag3 << endl;
return 0;
}
//The diagonals could be made into their own loop just incrementing the column every time you need a new diagonal since diag2 and diag3 loops are the same.
Sorry if it's messy (oh it is) and the identifies are terribly named but its 4am and I cant think straight anyway!
Anyways,the problem im having is in the calculation of diag2 and diag3. They both come out to be zero for some reason, if you simply cout the matrix at position [2][0] it will yield 7 and through a couple of debugging couts' I've found that it will multiply 2 and 6 to get 12 but then wont multiply 12 and 7 to get 84 which is what diag2 should yield.