Code Generation of Matrices and Arrays

MATLAB® and MATLAB Coder™ software store matrix data and arrays (1-D, 2-D, ...) in column-major format as a vector. Column-major format orders elements in a matrix starting from the first column, top to bottom, and then moving to the next column. For example, in the following 3x3 matrix:

A =
    1   2   3
    4   5   6
    7   8   9
translates to an array of length 9 in the following order:
A(1) = A(1,1) = 1; 
A(2) = A(2,1) = 4; 
A(3) = A(3,1) = 7; 
A(4) = A(1,2) = 2; 
A(5) = A(2,2) = 5;
and so on.

In column-major format, the software accesses the next element of an array in memory by incrementing the first index of the array. For example, the software stores these element pairs sequentially in memory:

  • A(i) and A(i+1)

  • B(i,j) and B(i+1,j)

  • C(i,j,k) and C(i+1,j,k)

For more information on the internal representation of MATLAB data, see MATLAB Data in the MATLAB External Interfaces document.

The code generator uses column-major format because:

  • Much of the software that supports signal and array processing uses column-major format: MATLAB, LAPack, Fortran90, DSP libraries.

  • A column is equivalent to a channel in frame-based processing. In this case, column-major storage is more efficient than row-major storage.

  • A column-major array is self-consistent with its component submatrices:

    • A column-major 2-D array is a simple concatenation of 1-D arrays.

    • A column-major 3-D array is a simple concatenation of 2-D arrays.

    • The stride is the number of memory locations to index to the next element in the same dimension. The stride of the first dimension is one element. The stride of the nth dimension element is the product of sizes of the lower dimensions.

    • Row-major n-D arrays have their stride of 1 for the highest dimension. Submatrix manipulations typically access a scattered data set in memory, which does not allow for efficient indexing.

C typically uses row-major format. MATLAB uses column-major format. You cannot configure the code generator to produce code with row-major ordering. If you are integrating legacy C code with the generated code, consider transposing the row-major data in your legacy C code into column-major format as a 1-D array.

Was this topic helpful?