The perks of Matlab’s column-major order

17 September 2015 in matlab

When working with Matlab, it’s good to remember the data are stored in the column-major order; otherwise, the following (seemingly harmless) code might cause a lot of trouble.

% both Positions and Normals are n x 3 matrices
file = ""
fid = fopen(file,'w');
% print Positions and Normals to file
fprintf(fid, '%f %f %f \t %f %f %f \n', [Positions Normals] );

So what’s the problem?

In this case, we expect the contents of the output file to have the form

Px1 Py1 Pz1   Nx1 Ny1 Nz1
 ⋮  ⋮  ⋮     ⋮  ⋮  ⋮
Pxn Pyn Pzn   Nxn Nyn Nzn

Instead, we get something completely different and meaningless:

Px1 Px2 Px3   Px4 Px5 Px6
 ⋮  ⋮  ⋮    ⋮   ⋮  ⋮
            …         Nzn

In case you forget, good luck debugging this!