Skip to content
Prev 47267 / 63424 Next

Matrix memory layout R vs. C

Hi Larissa,
<snip>

R uses column-major order [1] because that's the order used by FORTRAN and R
uses many libraries with a FORTRAN interface (most important: BLAS and LAPACK
for numerical linear algebra.) That's the situation with many other languages
/ libraries that use similar interfaces, such as MATLAB, Octave, Julia, and
Scilab [1]. So, there's no way around it and you just have to get used to
referencing matrix entries in col-major order.

[1] http://en.wikipedia.org/wiki/Row-major_order
<snip>

Try this instead:

#include <stdlib.h>
#include "R.h"

void printMatrix(int *mPtr, int m, int n) {
  int j,k;

  for(j = 0; j < m; j++){
    for(k = 0; k < n; k++) {
      printf("%d\t", mPtr[j + m * k]);
    }
    printf("\n");
  }
}
Specifying byrow=TRUE only changes how the matrix is *read*, not how it's
stored. A matrix -- and, more generally, an array -- is in fact just a vector
with (dimension) attributes, but that just specifies the memory layout of the
matrix, and not its representation (that is, it doesn't help.) Unfortunately,
there's no way to avoid this, but it shouldn't be too bad to get used to it.
:)

Cheers,
Luis

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso