Subversion Repositories gelsvn

Rev

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