Why, if MATLAB is column-major, do some functions output row vectors? Why, if MATLAB is column-major, do some functions output row vectors? arrays arrays

Why, if MATLAB is column-major, do some functions output row vectors?


It is a good question. Here are some ideas...

My first thought was that in terms of performance and contiguous memory, it doesn't make a difference if it's a row or a column -- they are both contiguous in memory. For a multidimensional (>1D) array, it is correct that it is more efficient to index a whole column of the array (e.g. v(:,2)) rather than a row (e.g. v(2,:)) or other dimension because in the row (non-column) case it is not accessing elements that are contiguous in memory. However, for a row vector that is 1-by-N, the elements are contiguous because there is only one row, so it doesn't make a difference.

Second, it is simply easier to display row vectors in the Command Window, especially since it wraps the rows of long arrays. With a long column vector, you will be forced to scroll for much shorter arrays.

More thoughts...

Perhaps row vector output from linspace and logspace is just to be consistent with the fact that colon (essentially a tool for creating linearly spaced elements) makes a row:

>> 0:2:16ans =     0     2     4     6     8    10    12    14    16

The choice was made at the beginning of time and that was that (maybe?).

Also, the convention for loop variables could be important. A row is necessary to define multiple iterations:

>> for k=1:5, k, endk =     1k =     2k =     3k =     4k =     5

A column will be a single iteration with a non-scalar loop variable:

>> for k=(1:5)', k, endk =     1     2     3     4     5

And maybe the outputs of linspace and logspace are commonly looped over. Maybe? :)

But, why loop over a row vector anyway? Well, as I say in my comments, it's not that a row vector is used for loops, it's that it loops through the columns of the loop expression. Meaning, with for v=M where M is a 2-by-3 matrix, there are 3 iterations, where v is a 2 element column vector in each iteration. This is actually a good design if you consider that this involves slicing the loop expression into columns (i.e. chunks of contiguous memory!).