Transpose 2d vector

I am trying to extract data from multiple files into one output file.
At the moment I am able to extract the columns I want into a vector in a vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
vector< vector<double> > out;   //2D vector
ofstream myfile ("example.txt");    //outputfile

//the data contained in data[n][6] is put into the vector called 'out'.
for(int i = 1; i < iNumberOfFiles+1 ; i++) {
	vector<double> row;	
	for (int n = 79; n < data.size(); n++) {
		row.push_back(data[n][6]);
	}  
	out.push_back(row);
}

//print the data in myfile
for(int i=0;i<out.size(); i++) {
	for (int j=0;j<out[i].size(); j++)
		myfile << out[i][j] << " ";
	myfile << endl; 
}
/*
Now here comes my problem, the data is put out as
a1	a2	a3	….	aN
b1	b2	b3	….	bN
.	.	.	….	...
x1	x2	x3	…	xN

but I need the data in the following form:
a1	b1	.	x1
a2	b2	.	x2
.	.	.	.
aN	bN	.	xN
*/

/

//I though the data could be transposed like  a 'normal' 2d array
vector< vector<double> > outtrans;   //the 'transposed' vector
for(int i=0;i<out.size(); i++) {   
	for (int j=0;j<out[i].size(); j++){
	        outtrans[j][i] = out [i][j];
	}
}
/* this is not working well however, when running this code, it (windows) says
file.exe is not functioning properly */


Does anyone have tips of how to transpose my vector properly (vector< vector<double> > out)?
Last edited on
If you expect to be working with matrices and do matrix operations, consider using a matrix library. There is the lightweight header-only boost.ublas (http://www.boost.org/doc/libs/release/libs/numeric/ublas/doc/index.htm) and more robust Eigen (http://eigen.tuxfamily.org), and others. Transposition can be optimized in remarkable ways which cannot be achieved with a vector of vectors.

But to get your code to work, give your outtrans sufficient size. Your outtrans is empty and any outtrans[i][j] access is wrong.

Assuming out is rectangular (this could be tested during input), you could:
1
2
3
4
5
    vector<vector<double>> outtrans(out[0].size(),
                                    vector<double>(out.size()));
    for (size_t i = 0; i < out.size(); ++i)
        for (size_t j = 0; j < out[0].size(); ++j)
            outtrans[j][i] = out[i][j];

demo: http://ideone.com/sVhtl
Last edited on
Many thanks for your quick reply. Indeed it was getting stuck at my 'transposing', before which I had not allocated the memory properly.

Thanks for the references to available matrix libraries. I am aware of boost.org, but had never heard of Eigen.

Apart from transposing, I don't expect to be doing much other matrix operations.
Well, for the moment at least...currently I am just at the stage of getting data in the correct format for fitting later...
Topic archived. No new replies allowed.