I have a matrix A stored in column major order as

1 3 2 4

and I'm using this function to output it in row major order, i.e.

1 2 3 4

which is does correctly. However I'm confused about how it does this, as I thought the loops would work by going i = 0 j =0, i = 0 j = 1, i = 1 j = 0, i = 1 j = 1.

But this would give me

data[0]
data[1]
data[2]
data[3]

my original matrix? Can anyone please explain this as I'm baffled?!

Thanks in advance!

void Matrix::WriteToFile(std::string fname) const
{
    ofstream myfile;
    myfile.open ( (fname+".txt").c_str() );

    for (int i = 0; i<mdim_; i++)
    {
    for (int j = 0; j<ndim_; j++)
    {
        myfile << data_[i * ndim_ + j] << " ";
    }
    }
    myfile.close();
}

Isn't row- or column-major done like this?

#include <stdio.h>

void col_major(int *data, int rows, int cols)
{
   size_t i, j;
   puts("column major:");
   for ( i = 0; i < rows; ++i )
   {
      for ( j = 0; j < cols; ++j )
      {
         int index = i * cols + j;
         printf("data[%d] = %d\n", index, data[index]);
      }
   }
}

void row_major(int *data, int rows, int cols)
{
   size_t i, j;
   puts("row major:");
   for ( i = 0; i < rows; ++i )
   {
      for ( j = 0; j < cols; ++j )
      {
         int index = j * rows + i;
         printf("data[%d] = %d\n", index, data[index]);
      }
   }
}

int main(void)
{
   int data[] = 
   { 
      1, 4, 7, 
      2, 5, 8, 
      3, 6, 9, 
   };
   col_major(data, 3, 3);
   row_major(data, 3, 3);
   return 0;
}

/* my output
column major:
data[0] = 1
data[1] = 4
data[2] = 7
data[3] = 2
data[4] = 5
data[5] = 8
data[6] = 3
data[7] = 6
data[8] = 9
row major:
data[0] = 1
data[3] = 2
data[6] = 3
data[1] = 4
data[4] = 5
data[7] = 6
data[2] = 7
data[5] = 8
data[8] = 9
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.