Subversion Repositories gelsvn

Rev

Rev 30 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
30 jab 1
#include "LinAlgIO.h"
2
#include <fstream>
3
#include <iostream>
4
#include <algorithm>
5
#include <vector>
6
 
7
using namespace std;
8
 
9
namespace
10
{
11
 
12
	bool Comp(istreambuf_iterator<char>& Itt,const string str)
13
	{
37 bj 14
 
30 jab 15
		int cChar=0;
16
		bool Ret=true;
17
		while(cChar<str.size() && Ret)
18
		{
19
			Ret=(*Itt==str[cChar]);
20
			++Itt;
21
			cChar++;
22
		}
23
 
24
		return Ret;
25
	}
26
 
27
	bool FindVar(istreambuf_iterator<char>& Itt,
28
		istreambuf_iterator<char> End,
29
		const string VarName)
30
	{
31
		bool bFound=false;
32
 
33
		while(!bFound)
34
		{
35
			Itt=find(Itt,End,VarName[0]);
36
			if(Itt==End)
37
				return false;
38
			bFound=Comp(Itt,VarName);
39
		}
40
 
41
		return true;
42
	}
43
 
44
 
45
}
46
 
47
namespace LinAlg
48
{
49
void ToMatlab(const CMatrix& A,
50
			  const std::string& VarName,
51
			  const std::string& FileName,
52
			  const bool append,
53
			  const std::string& Comment)
54
{
37 bj 55
	long nMode;
30 jab 56
	if(append)
57
		nMode=std::ios::app;
58
	else
59
		nMode=std::ios::trunc;
37 bj 60
	std::ofstream Mfile(FileName.c_str(), nMode);
30 jab 61
 
37 bj 62
 
30 jab 63
	if(!Comment.empty())
64
		Mfile << "% " << Comment.c_str() << "\n";
65
	Mfile << VarName.c_str() << "=[";
66
 
67
 
68
	const double* pRow;
69
 
70
	for(int cRow=0;cRow<A.Rows();cRow++)
71
	{
72
		pRow=A[cRow];
73
		for(int cCol=0;cCol<A.Cols();cCol++)
74
		{
75
			Mfile << "\t" << pRow[cCol];
76
		}
77
		Mfile << ";\n";
78
	}
79
 
80
	Mfile << "];\n\n";
81
}
82
 
83
 
84
void FromMatlab(CMatrix& A,
85
				const std::string& VarName,
86
				const std::string& FileName)
87
{
88
	ifstream file(FileName.c_str());
89
	istreambuf_iterator<char> Itt(file);
90
	istreambuf_iterator<char> End;
91
 
92
	string VarId(VarName);
93
	VarId+="=[";
94
 
95
	FindVar(Itt,End,VarId);
96
 
97
	vector<double> data;
98
	double elem;
99
	int nCols=0;
100
 
101
	while((*Itt)!=';')	
102
	{
103
		Itt=(file >> elem );
104
		data.push_back(elem);
105
		nCols++;
106
	}
107
 
108
	Itt++;
109
	Itt++;
110
	int nElems=nCols;
111
 
112
	while((*Itt)!=']')
113
	{
114
		while((*Itt)!=';')	
115
		{
116
			Itt=(file >> elem );
117
			data.push_back(elem);
118
			nElems++;
119
		}
120
		Itt++;
121
		Itt++;
122
	}
123
 
124
	A.Resize(nElems/nCols,nCols);
125
 
126
	memcpy(A[0],&(data[0]),sizeof(double)*data.size());
127
 
128
 
129
/*	for(int cI=0;cI<20;cI++)
130
	{
131
		cout << *Itt;
132
		++Itt;
133
	}
134
*/
135
/*	for(int cI=0;cI<data.size();cI++)
136
		cout << data[cI] << "\t";
137
 
138
	cout << endl << nCols << endl << nElems << endl;
139
*/
140
 
141
}
142
 
143
}