二维矢量双打排序/编辑问题

时间:2017-04-20 15:45:33

标签: c++ sorting matrix

我正在研究双向矩阵求解器的二维矢量,我的矩阵不正确地输出。 “Level 3”的预期矩阵输出是{(从上到左)3,4(从上到下,从左到右)1,2}但我的代码仍然输出{2,1超过3,4}。我一直试图反转这些值,但每当我这样做时,我都会遇到超出界限的异常。

 vector<double> gauss(mat B) {

 int n = B.A.size();

    for (int i=0; i<n-1; i++) {
    // Search for maximum in this column
    double maxEl = abs(B.getSlot(i,i));
    int maxRow = i;
    for (int k=i+1; k<n; k++) {
        if (abs(B.getSlot(k,i)) > maxEl) {
            maxEl = abs(B.getSlot(k,i));
            maxRow = k;
        }
    }

    // Swap maximum row with current row
    for (int k=i; k<n+1;k++) {
        double tmp = B.getSlot(k,maxRow);
        B.editSlot(k,maxRow,B.getSlot(k,i));
        B.editSlot(k,i,tmp);
    }
 cout << "\n\nlevel 3: \n";
 B.display();

}
B.display();

// Solve equation Ax=b for an upper triangular matrix A
vector<double> x(n);

for (int i=n-1; i>=0; i--) {
    x[i] = B.getSlot(i,n)/B.getSlot(i,i);
    for (int k=i-1;k>=0; k--) {
        B.editSlot(k,n,B.getSlot(k,n)-B.getSlot(k,i)*x[i]);
    }
}
return x;
}


int main() {

int n = *Size of array is properly retrieved*

mat my_mat(n,n);

// Read input data
for (int i=0; i<n; i++) {
    for (int j=0; j<n; j++) {
        double myDub;
        inFile >> myDub;
        my_mat.editSlot(i,j,myDub);

    }
}

// Calculate solution
vector<double> x(n);
x = gauss(my_mat);
}

我的班级代码如下

class mat
{
public:

mat(int x,int y){
 int row = x;
  int col = y;
    n=row;

    A = vector<vector<double>>(row,vector<double>(row,0));


    for(int i=0; i<row; i++)
            {
                for(int j=0; j<col; j++)
                {
                    cout<<setw(6)<<A[i][j];
                }
                cout<<endl;
            }
        }

        void editSlot(int x, int y, double val){A[y][x] = val;}
        double getSlot(int x, int y){return A[y][x];}

     void display()
        {
            for(int i=0; i<n; i++)
            {
                for(int j=0; j<n; j++)
                {
                    cout<<setw(6)<<A[j][i];
                }
                cout<<endl;
            }
            cout<<endl;
        }





 vector<vector<double>> A;

 private:
 int n;

 };

1 个答案:

答案 0 :(得分:0)

尝试更改输入循环:

// Read input data
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        double myDub;
        inFile >> myDub;
        my_mat.editSlot(j, i, myDub);  // < - j, i swapped.
    }
}

您能提供您使用的样本输入以及您期望的输出吗?