Is MATLAB row specific or column major?
It is important to understand that MATLAB stores data in column-major order, so you know what happens when you apply the colon
operator without any commas:
>> M = magic(3)
M =
8 1 6
3 5 7
4 9 2
>> M(:)
ans =
8
3
4
1
5
9
6
7
2
I tend to think "MATLAB goes down, then across". This makes it easy to reshape
and permute
arrays without scrambling your data. It's also necessary in order to grasp linear indexing (e.g. M(4)
).
For example, a common way to obtain a column vector inline from some expression that generates an array is:
reshape(<array expression>,[],1)
As with (:)
this stacks all the columns on top of each other into single column vector, for all data in any higher dimensions.
But this nifty syntactic trick lets you avoid an extra line of code.
In MATLAB, arrays are stored in column major order.
It means that when you have a multi-dimensional array, its 1D representation in memory is such that leftmost indices change faster.
It's called column major order because for a 2D array (matrix), the first (leftmost) index is typically the row index, so since it changes faster than the second (next to the right) index, the 1D representation of the matrix is memory correspond to the concatenation of the columns of the matrix.