Why are vectors horizontally and matrices vertically indexed?

12 views (last 30 days)
Why are vectors horizontally and matrices vertically indexed? I'm sure it has it has its origin in linear algebra, but it leads to a whole lot of unexpected behaviour.
For instance:
A = 1:10; % is a horizontal vector
plot(A,A); % will give a single straight line
% but when put in a matrix
plot([A;A],[A;-A]); %indexing works from top to bottom and we get a set of ten lines
Another example:
% Defining some variables for a table
city{1} = 'paris'; city{2} = 'milan'; city{3} = 'new york';
pop(1) = 2.2e6; pop(2) = 1.4e6; pop(3) = 19.7e6;
% and creating the table
table(city, pop)
ans =
city pop
________________________________ _______________________________
'paris' 'milan' 'new york' 2.2e+06 1.4e+06 1.97e+07
% horizontal vectors are treated as lists of variables, in stead of series.
I know its a matter of proper bookkeeping or using (:) with vectors to return a column vector. I just wonder if I'm missing something here which you might be able to clear up.

Answers (1)

Alessandro Masullo
Alessandro Masullo on 5 Feb 2015
Matlab variables are always indexed vertically. What you are talking about is a plot behaviour:
plot(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, disconnected
line objects are created and plotted as discrete points vertically at
X.
  1 Comment
Guillaume
Guillaume on 5 Feb 2015
Edited: Guillaume on 5 Feb 2015
Alessandro in correct in that linear indexing works vertically first (matlab is row-major) and that the behaviour you see is due to special casing by plot.
There are unfortunately many many functions that special-case matrices vs vector in matlab, making it very difficult to write generic code that behaves the same regardless of the size of the input.
For example, even basic indexing has special cases. A(B) is the same shape as B, unless both are vectors, in which case it's the same shape as A. Crazy, huh?

Sign in to comment.

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!