c++ - 高斯消去码

标签 c++ matrix

我曾尝试编写代码,从 nxn 矩阵中读取值,然后将这些值打印出来。我想我已经成功地做到了这一点。我尝试的下一步是使用高斯消元法求解矩阵,但我无法获得打印出值的代码。有人可以看看这个并告诉我哪里出错了吗?

  #include <cstdlib>
  #include <cmath>
  #include <vector>
  #include <iostream>
  #include <fstream>
  #include <string>

  using namespace std;


   int main(){
   //create a 2D vector of doubles 
   vector< vector< double > > matrix; 


    int num_lines = 0;
    double temporary, r;
    int i, j, k, dimension, temp; /* counter variables for loops */




    // Open a file containing the matrix data
    ifstream myFile("test_data2.txt");
    // Check if file is open
    if(myFile.is_open()){
    // First step is to detect matrix size by assuming matrix is
    // square and counting number of columns.

    // Tempoary variable to hold current line to process
    string line;

    // Tempoary variable to hold number of rows and cols in square matrix
    int num_lines = 0;

    // Count rows / cols
    while(getline(myFile, line)){
        num_lines ++;
    }

    // Reset EOF flag
    myFile.clear();

    // Reset to start of file
    myFile.seekg(0, myFile.beg);

    // Second step is to grab lines from the file and process them
    // splitting each line into substrings and converting them into
    // doubles

    // For each line
    for(int l = 0; l < num_lines; l ++){
        // Process line by line
        getline(myFile, line);

        // Tempoary vector to hold rows of matrix data
        vector<double> temp;

        // Tempoary variable to hold search positions
        int start = 0;
        int end;
        int length;

        // Get value by value
        for(int n = 0; n < num_lines; n ++){
            // Break line down by finding commas
            end = line.find(',', start);
            length = end - start;

            // Extract substring
            string tempstr = line.substr(start, length);

            // Set next value of start
            start = end + 1;

            // Convert to double
            temp.push_back(atof(tempstr.c_str()));
        }

        // Add row to matrix
        matrix.push_back(temp);
    }
    // Close input file
    myFile.close();
} else {
    // If input file failed to open, print an error
    cout << "Error opening input file" << endl;
}
// Print out the matrix (will do nothing if input file open failed)
cout << "Print out input file." << endl;

for(int i = 0; i < matrix.size(); i ++)
{
    for(int j = 0; j < matrix[i].size(); j ++)
    {
        cout << matrix[i][j];
        // Add commas and new lines when required
        // Remember not to add commas after rightmost values, or
        // a new line at the end of the last value
        if(j < matrix[i].size() - 1)
        {
            cout << ' '; // Character, not string
        }
        else
        {
            if(i < matrix[i].size() - 1)
            {
                cout << '\n'; // Character, not string
            }
        }
    }
}






 for (i = 0; i < num_lines; i++)
    for (j = num_lines; j < 2 * num_lines; j++)
        if (i == j % num_lines)
            matrix[i][j] = 1;
        else
            matrix[i][j] = 0;

  /* using gauss-jordan elimination */
  for (j = 0; j < num_lines; j++) {
    temp = j;

    /* finding maximum jth column element in last (dimension-j) rows */
    for (i = j + 1; i < num_lines; i++)
        if (matrix[i][j] > matrix[temp][j])
            temp = i;



    /* swapping row which has maximum jth column element */
    if (temp != j)
        for (k = 0; k < 2 * num_lines; k++) {
            temporary = matrix[j][k];
            matrix[j][k] = matrix[temp][k];
            matrix[temp][k] = temporary;
        }

      /* performing row operations to form required identity matrix out of the input              matrix */
    for (i = 0; i < num_lines; i++)
        if (i != j) {
            r = matrix[i][j];
            for (k = 0; k < 2 * num_lines; k++)
                matrix[i][k] -= matrix[j][k] * r / matrix[j][j];
        } else {
            r = matrix[i][j];
            for (k = 0; k < 2 * dimension; k++)
                matrix[i][k] /= r;
        }
   }

   /* Display augmented matrix */
   printf("\n After Gauss-Jordan elimination, augmented matrix is : \n\n");

  for (i = 0; i < num_lines; i++) {
     for (j = 0; j < 2 * num_lines; j++)
        printf("  %4.2f", matrix[i][j]);
      printf("\n");
   }


   /* displaying inverse of the non-singular matrix */
   printf("\n\n\n The inverse of the entered non-singular matrix is : \n\n");

    for (i = 0; i < num_lines; i++) {
    for (j = num_lines; j < 2 * num_lines; j++)
        printf("  %.5f", matrix[i][j]);
    printf("\n");
  }


 return 0;
  }

    // EXAMPLE FILE
    //1,2,3
    //4.5,6.7,8.8
    //-110,-55.3,+53.723
    // END OF EXAMPLE FILE REMOVE COMMENTS AT TOP AND BOTTOM AND "//" characters before    use. Save as "matrix.csv".

最佳答案

错误 1:

你声明

 int num_lines = 0;

在里面

 if(myFile.is_open())

阻止。因此,'num_lines++' 行在

 while(getline(....) )

循环,但随后 num_lines(第二个)未声明,所有循环(高斯消除和打印)仅迭代零次。

删除第二个 num_lines 声明。

错误 2:

“维度”变量永远不会被初始化。从逻辑上讲,它应该等于“num_lines”。

错误 3:

“矩阵”变量未正确初始化。你在那里 push_back 'temp' vector ,但只有 'num_lines' 长度,而不是 'num_lines * 2'。

PS:我不能保证没有更多的错误。

关于c++ - 高斯消去码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20271396/

相关文章:

c++ - 在另一个 C++ 中调用一个类的方法

c++ - 64 位平台上的 WinAPI IcmpSendEcho

c++ - 这是合法/安全的 C++ 吗? (向下转换为相同大小的继承类)

php - 有没有一个好的 PHP 向量和矩阵库?

Java:使用 EJML 的矩阵逆没有按预期工作

c++ - 我如何在 Eigen 中创建复数矩阵

c++ - 对右值引用 vector::push_back 函数如何提高效率感到困惑

C++ cout 自动分隔符

c++ - LAPACK 在 C++ 中的 QR 分解

matlab - 我如何判断矩形矩阵是否在 MATLAB 中有重复的行?