我有两种代码:
这个,我可以从mtx文件中提取所有字符,但是当我运行它时,我无法获得第一行的最后两个单词,不能跳过带有'%'字符并为空的行行,并且我无法将矩阵维及其值分成各自的数组。另外,第一行带有数字的整数是对维数和条目数进行计数的整数,并且我想创建一个for循环来对主目录进行计数,并在其自己的数组上分离值,以便可以用科学计数法计算它们的frobinius_norm。 >
#include <iostream>
#include <cmath>
#include <vector>
#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
void processLine(const string &line)
{
string first, second, third;
if ( line[0]&&line[1] == '%' )
{
//extract last 2 words
cout <<line << endl;
} else if (line[0]=='%')
{
//ignore the lines
cout << line << endl;
} else {
/*seperate matrix dimensions and values,
but the first one is x*y dimension and number of entries*/
cout << line << endl;
}
}
void processFile(const char *filename)
{
ifstream inf(filename);
if ( inf.is_open() ) {
string line,type;
while ( getline(inf,line) ) {
processLine(line);
}
} else {
cout << "Sorry, but the file don't exist!\n";
}
}
int main(int argc, char *argv[])
{
if (argc==2){
cout <<"Filename: " << argv[1] << endl;
processFile(argv[1]);
} else {
cout << "give a filename\n";
}
}
这个,我可以成功提取第一个矩阵文件上的所有信息: sparse01.mtx :
%% MatrixMarket矩阵坐标模式常规 9 9 50 1 1 2 1 4 1 5 1 6 1 7 1 8 1 9 1 2 2 3 2 ... 9 9
但是sparse02.mtx和sparse03.mtx矩阵无法修改代码以提供正确的结果,因为我无法忽略以'%'开头的行和空行。我无法真正计算主菜和分隔的维度和值,因此我无法计算frobinius范数...
int main(int argc, char *argv[])
{
string filename, line, type1, type2, header;
int x, y, entry, count=0;
double element;
char norm;
float frobenius_norm;
ifstream openfile;
filename = argv[1];
openfile.open(argv[1]);
if(!openfile.is_open())
{
cout << "Sorry, but the file don't exist!\n";
exit(1);
}
for(int i =0;i<2;i++)
{
getline(openfile,line,' ');
}
getline(openfile,header,' ');
getline(openfile,type1,' ');
getline(openfile,type2);
if(getline(openfile,line).peek()=='%'){
cout << "lol"<<endl;
}
openfile >> x >> y >> entry;
cout <<"Filename: " << filename << endl;
cout <<"Dimensions: " << x << " x " << y << endl;
cout <<"Entries: " << entry <<endl;
if(header == "coordinate")
{
cout <<"Sparse: "<< "true" <<endl;
}
else if ((x*y/2)<entry||header == "array")
{
cout <<"Sparse: "<< "false" <<endl;
}
cout <<"Type: "<< type1 << ' ' << type2 <<endl;
if(type1 == "pattern"){
norm = '-';
cout <<"Frobenius norm: "<< norm <<endl;
} else {
frobenius_norm = 100;
cout <<"Frobenius norm: "<< frobenius_norm <<endl;
}
return 0;
}
输出应该像这样
文件名:sparse01.mtx 尺寸:9 x 9 参赛作品:50 稀疏:正确 类型:一般模式 Frobenius规范:-
%% MatrixMarket矩阵坐标模式常规 9 9 50 1 1 2 1 4 1 5 1 6 1 7 1 ...(被截断) 9 9
sparse03矩阵的输出是这样的: 档名:sparse03.mtx 尺寸:5 x 5 参赛作品:10 稀疏:正确 类型:实数一般 Frobenius规范:1.2e + 02
这是sparse03.mtx文件(这不是代码,而是输入文件):
%%MatrixMarket matrix coordinate real general
%
% Hello
% How
% Are
% you
% doing
%
5 5 10
1 1 11.0
1 5 15.0
2 3 23.0
2 4 24.0
3 2 32.0
3 5 35.0
4 1 41.0
5 2 52.0
5 4 54.0
5 5 55.0
我还希望我的代码计算密集且特殊的矩阵:
请记住,我使用argv [1]作为输入参考