Eigen matrix vs for loop matrix give off results

Why is that if I print my matrix inside the for loop gives different results that when I print it outside?

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
#include <cmath>
#include<math.h>
#include<stdio.h>
#include <cstring>
#include <sstream>
#include <string>
#include <iostream> 
#include <vector>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <assert.h>
#include<valarray>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;
int main() {
    static const int ny = 10; 
    std::vector<double> ygl(ny+1); 
    Eigen::Matrix< double, ny+1, ny+1> dv;
	dv.setZero();
    
	for (int i = 0; i < ny+1; i++){
		for (int j = 0; j < ny+1; j++){
			ygl[j] = -1. * cos(((j) * EIGEN_PI )/ny);
			dv(j + ny*i) =   sin(acos(ygl[j]) * (i)); 
			cout << dv(j + ny*i) << "\n"; //this is correct
		}
	}
    // VS:
    std::cout << dv << "\n"; //this is off

    return 0;
}

I would like to use dv outside of the loop to perform matrix multiplication using Eigen.
Last edited on
You rows and columns have length ny+1. When you flatten your array you are using just ny.
@lastchance But when I print dv std::cout << dv << "\n"; I get a matrix with size ny+1 * ny+1 just with off values. I am not sure I understand.
@lastchance nvm actually you're right, when I change my index in the for loop to ny I get the same dv outside of the for loop. Now, what I want is to have the correct size(ny+1 * ny+1). I tried using dv.resize(ny+1,ny+1); and replicate as well and both give error messages and do not work. What is the correct approach here?
dvij is written using the syntax dv(i, j)

See:
https://godbolt.org/z/oMYez53aq
Last edited on
@mbozzi
dvij is written using the syntax dv(i, j)

oh well, you're right!
Allow me to ask few stupid question. I guess, I was indexing j + ny*i which in my head made sense and was working fine to this point so idk why is it wrong here. And when I index dv(j,i) I get the exact correct results to my MATLAB code vs (i,j) which returns few signs off.
Finally Thanks A LOT!
I was indexing j + ny*i

The matrix has ny+1 rows and columns so to access column j row i you'd need to say dv(j + (ny + 1)*i). Notice that Eigen does use a column-major storage order hence why you might have got the indices backward, especially since C++ programmers use row-major order by convention.

dv(j + (ny + 1)*i)

oh yeah this is it, I have completely missed this. Also, I keep forgetting about Eigen uses column-major storage. I will need to be more careful moving forward since I am switching to Eigen now. Thanks again btw.
Topic archived. No new replies allowed.