0

I have the following code:

static const int nx = 4; 
static const int ny = 4;
static const int nz = 4;

Eigen::Tensor<double, 3> test((nz+1),nx,ny); 
test.setZero(); //ttt1.setRandom(); 
    for(int i = 0; i< nx; i++){
        for(int j = 0; j< ny; j++){
            for(int k = 0; k< nz+1; k++){ 
                test(j + (nz+1)*i+k) = (i)*dx;  
            }

        }       
    }

This code produces the following output:

0  1.5708 3.14159 4.71239 4.71239       0       0       0       0       0       0       0       0       0       0       0
  0  1.5708 3.14159 4.71239 4.71239       0       0       0       0       0       0       0       0       0       0       0
  0  1.5708 3.14159 4.71239 4.71239       0       0       0       0       0       0       0       0       0       0       0
  0  1.5708 3.14159 4.71239       0       0       0       0       0       0       0       0       0       0       0       0
  0  1.5708 3.14159 4.71239       0       0       0       0       0       0       0       0       0       0       0       0

which is sort of correct, but not fully initialize the tensor correctly this should be more like:

 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 ..
 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 ..
 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 ..
 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 ..
 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 0    1.5708    3.1416    4.7124 ..

Repeating in such a way that the tensor is a 5-by-4-by4. I am using tensor to reproduce 3D matrix from MATLAB, so I am new to tensor. Thanks.

Jamie
  • 365
  • 2
  • 5
  • 13
  • 1
    This is due to the way floating point values are printed to stdout stream rather than the way eigen stores them. You can refer to this [post](https://stackoverflow.com/questions/20135901/c-cout-double-not-printing-decimal-places). – kalgoritmi Sep 05 '22 at 04:02
  • 1
    If you would like to reproduce the way Matlab prints them then you have to set the precision to 5 digits using `iomanip`'s `setprecision` and the floating-point notation to `fixed`, here is an [example](https://cplusplus.com/reference/iomanip/setprecision/). – kalgoritmi Sep 05 '22 at 04:18
  • 1
    You also need to multiply `k` by `nx*ny` or `j` by `nx*(nz+1)` -- depending on what order you want. Or let Eigen do the scaling and use `test(k,i,j) = i*dx;` (or using a different order). – chtz Sep 05 '22 at 09:56
  • @chtz Thanks! test(k,i,j) works better and similarly to MATLAB's meshgrid function. – Jamie Sep 06 '22 at 18:31

0 Answers0