Row-Major and Column-Major Array Layouts
The elements of an array can be stored in column-major layout or row-major layout. For an array stored in column-major layout, the elements of the columns are contiguous in memory. In row-major layout, the elements of the rows are contiguous. Array layout is also called order, format, and representation. The order in which elements are stored can be important for integration, usability, and performance. Certain algorithms perform better on data stored in a particular order.
Programming languages and environments typically assume a single array layout for all data. MATLAB® and Fortran use column-major layout by default, whereas C and C++ use row-major layout. With MATLAB Coder™, you can generate C/C++ code that uses row-major layout or column-major layout. See Generate Code That Uses Row-Major Array Layout.
Array Storage in Computer Memory
Computer memory stores data in terms of one-dimensional arrays. For example, when you declare a 3-by-3 matrix, the software stores this matrix as a one-dimensional array with nine elements. By default, MATLAB stores these elements with a column-major array layout. The elements of each column are contiguous in memory.
Consider the matrix
A = 1 2 3 4 5 6 7 8 9
A is represented in memory by default with this
1 4 7 2 5 8 3 6 9
In row-major array layout, the programming language stores row elements contiguously in memory. In row-major layout, the elements of the array are stored as:
1 2 3 4 5 6 7 8 9
N-dimensional arrays can also be stored in column-major or row-major layout. In column-major layout, the elements from the first (leftmost) dimension or index are contiguous in memory. In row-major, the elements from the last (rightmost) dimension or index are contiguous.
Conversions Between Different Array Layouts
When you mix row-major data and column-major data in the same code, array layout conversions are necessary. For example, you can generate code that includes row-major and column-major function specializations. Function specializations use one type of array layout for all input, output, and internal data. When passing data between functions, the code generator automatically inserts array layout conversions as needed. Input and output data to generated MEX functions is also converted as needed.
For two-dimensional data, transpose operations convert data between row-major
layout and column-major layout. Consider the transposed version of
A' = 1 4 7 2 5 8 3 6 9
The column-major layout of
A' matches the row-major layout of
A. (For complex numbers, array layout conversions use a