title: MATLAB Tensor Indexing in C++
body: <p>I am attempting to load in a .mat file containing a tensor of known dimensions in C++; <code>144x192x256</code>.</p>
  
  <p>I have adjusted the linear index for the read operation to be column major as in MATLAB. However I am still getting memory access issues. </p>
  
  <pre><code>void FeatureLoader::readMat(const std::string &amp;fname, Image&lt; std::vector&lt;float&gt; &gt; *out) {
      //Read MAT file.
      const char mode = 'r';
      MATFile *matFile = matOpen(fname.c_str(), &amp;mode);
      if (matFile == NULL) {
          throw std::runtime_error("Cannot read MAT file.");
      }
  
  
      //Copy the data from column major to row major storage.
      float *newData = newImage-&gt;GetData();
      const mxArray *arr = matGetVariable(matFile, "map");
      if (arr == NULL) {
          throw std::runtime_error("Cannot read variable.");
      }
  
      double *arrData = (double*)mxGetPr(arr);
  #pragma omp parallel for
      for (int i = 0; i &lt; 144; i++) {
  #pragma omp parallel for
          for (int j = 0; j &lt; 192; j++) {
              for (int k = 0; k &lt; 256; k++) {
                  int rowMajIdx = (i * 192 + j) * 256 + k;
                  int colMajIdx = (j * 144 + i) * 256 + k;
                  newData[rowMajIdx] = static_cast&lt;float&gt;(arrData[colMajIdx]);
              }
          }
      }
  }
  </code></pre>
  
  <p>In the above snippet, am I right to be accessing the data linearly as with a flattened 3D array in C++? For example:-</p>
  
  <pre><code>idx_row_major = (x*WIDTH + y)*DEPTH + z
  idx_col_major = (y*HEIGHT + x)*DEPTH + z
  </code></pre>
  
  <p>Is this the underlying representation that MATLAB uses?</p>