我的Matrix
A.第一版
这个小程序是最初的版本。
1。 程序基本说明:这是一个实现矩阵各种运算的类,目前仅仅实现了从文件读取矩阵,将矩阵化简为echelon form和reduced echelon
form.
2。 程序思路:我的类功能还很简单,通过一个内置的二维数组记录矩阵的entry。
3。 主要函数介绍:
A. void readFromFile(const char* fileName);从文件读取矩阵,以换行符作为矩阵行数增加的标志,我利用了ifstream的
成员函数peek()每次去偷窥一下是否为换行符,是的话就将矩阵行数加一,同时将列数更新,当然最后一行会因为文件结束而只能强
行加一。
B. void echelon(int r, bool reduced=true);化简为echelon form的函数,首先从0行调用,找到不为0的entry然后将其化简
为1,然后将行数参数r加1,以递归调用。参数reduced默认化简为最简echelon form.
4。 不足之处:
A. 时间比较少,方法写的比较粗糙。
B. 还没有实现矩阵的加碱法,乘法。
#include <iostream> #include <fstream>
using namespace std;
const MaxRow = 10; const MaxCol = 10;
class Matrix
{
private:
int rowNum;
int colNum;
double lst[MaxRow][MaxCol];
void mul(int source, int dest, double scalor);
public:
Matrix();
int row() const {return rowNum;}
int col() const {return colNum;}
void setRow(const int newRow) { rowNum = newRow;}
void setCol(const int newCol) { colNum = newCol;}
void display();
double& items(int r, int c);
void initialize();
void readFromFile(const char* fileName);
void echelon(int r, bool reduced=true);
};
int main()
{
Matrix M;
M.readFromFile("c:\\nick.txt");
M.echelon(0);
M.display();
cout<<"\n\n"<<"row is:"<<M.row(); cout<<"\ncol is:"<<M.col()<<endl; return 0; }
void Matrix::echelon(int r, bool reduced)
{
int c=r;
if (r<rowNum)
{
while (c< colNum)
{
if (lst[r][c] ==0)
{
c++;
}
else
{
mul(r, r, (1-lst[r][c])/lst[r][c]);
for (int i=(!reduced?r+1:0); i< rowNum; i++)
{
if (i!=r)
{
mul(r, i, -lst[i][c]);
}
}
echelon(r+1, reduced);
break;
}
}
}
}
void Matrix::mul(int source, int dest, double scalor)
{
for (int c=0; c< colNum; c++)
{
lst[dest][c] += lst[source][c]*scalor;
}
}
double& Matrix::items(int r, int c)
{
return lst[r][c];
}
void Matrix::readFromFile(const char* fileName)
{
int r=0, c=0;
char ch;
ifstream f;
f.open(fileName);
while (!f.eof())
{
ch = f.peek();
if (ch!=10)
{
f>>lst[r][c];
c++;
if (c>colNum)
colNum = c;
}
else
{
f.ignore();
r++;
setCol(c);
c =0;
}
}
if (r!=0)
{
setRow(r+1);
}
}
void Matrix::initialize()
{
for (int r=0; r < rowNum; r++)
{
for (int c=0; c< colNum; c++)
{
lst[r][c] = r*2+c;
}
}
}
void Matrix::display()
{
int temp;
long preFlag;
preFlag = cout.flags();
temp = cout.precision(4);
// cout.setf(ios::fixed|ios::showpoint);
cout<<"row\\col";
for (int c=0; c< colNum; c++)
{
cout<<"\t"<<c;
}
cout<<"\n\n";
for (int r = 0; r< rowNum; r++)
{
cout<<r;
for (c = 0; c< colNum; c++)
{
cout<<"\t"<<lst[r][c];
}
cout<<endl;
}
cout.precision(temp);
cout.flags(preFlag);
}
Matrix::Matrix()
{
rowNum = 5;
colNum = 5;
initialize();
}