Okay, I am pulling out all my hair on this one, though, as a noob, I am sure there are several problems. I want to take a matrix and, by sing elementary row operations, reduced it to row-reduced echelon form. We assume (1) it is solvable and (2) a unique solution. There is no checking for zeros or anything; it just does row operations. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce (float A[][4]);
int main()
{
float A[3][4] = {{5, -6, -7, 7}, {3, -2, 5, -17}, {2, 4, -3, 29}}; //answer should be {2, 4, -3}
printmatrix(A);
RowReduce(A);
}
void printmatrix(float A[][4]){ // Outputs the matrix
int p=3;
int q=4;
for (int i=0; i<p; i++)
{
for (int j=0; j<q; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
}
void RowReduce (float A[][4]){
int p=3; //rows
int q=4; //columns
int lead = 0; //the determines the column we are at which holds the diagonal, the basis for all elimination above and below
cout << endl;
while (lead<q-1)
{
for (int i=0; i<p; i++) //for each row . . .
{
if (i!=lead) // ignore the diagonal, and we will not have a tree rref as the diagonal will not be divided by itself. I can fix that.
{
cout << A[lead][lead] << " " << A[i][lead];
for (int j=0; j<q; j++)
{
A[i][j]=A[lead][lead]*A[i][j]; //here is the math . . . . probably where the problem is?
A[i][lead]=A[i][lead]*A[lead][j];
A[i][j]=A[i][j]-A[i][lead];
}
cout << endl;
}
}
lead++; // now go to the next pivot
cout << endl;
}
}
I tried doing it by hand, but what I get is, of course, the right answer, but this gets a diagonal matrix--which is great--but the wrong answer!
Aucun commentaire:
Enregistrer un commentaire