0
$\begingroup$

I am new to linear algebra (I am learning it as part of a machine learning course) and one persistent confusion has been the usage of row vs column vectors. In my programming background we would use "row vectors" 100% of the time because that is how they are written in code, but when linear algebra is used in lectures it varies a lot, and it also varies in MATLAB.

Here is an example where it can vary in MATLAB.

>> A = [1 2 3; 4 5 6; 7 8 9;]

A =

     1     2     3
     4     5     6
     7     8     9

>> v = [1 2 3 4 5 6]

v =

     1     2     3     4     5     6

>> A(:)

ans =

     1
     4
     7
     2
     5
     8
     3
     6
     9

So when I created a vector, MATLAB printed it back to me as a row matrix. Then when I used the special notation A(:) to get the matrix A back as a vector, it gave it to me as a column matrix.

So are row vectors still the default and there's just something special about the notation A(:)?

1 Answers 1

3

MATLAB stores matrices in column-major order. This is one trait MATLAB inherited from FORTRAN, together with 1-based indexing with round parentheses, and a name spelled in all caps.

When you use linear indexing, as in A(:), you are effectively accessing elements in the order in which they are stored. As another example, reshape(1:12,3,4) produces the matrix [1 4 7 10; 2 5 8 11; 3 6 9 12], because reshape does not move the data, only changes how they are divided in columns.

Functions like sum or any also run down the columns of a two-dimensional array to produce a one-dimensional row vector in one linear traversal.

Storage of a vector is unaffected by the choice of order, and transposing a vector is a constant time operation in MATLAB. All that is needed is swapping the number of rows with the number of columns.

There are some aspects of MATLAB where one may perceive a bit of inconsistency. For instance, subplot(2,2,2) (divide the plotting window in two rows and two columns and select the second of the four parts) selects the subplot in row 1, column 2, but by and large, knowing that the memory layout is column-major helps one predict the results of matrix manipulations and write more efficient code.