Why are vectors horizontally and matrices vertically indexed?

15 次查看(过去 30 天)
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.

回答(1 个)

Alessandro Masullo
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 个评论
Guillaume
Guillaume 2015-2-5
编辑:Guillaume 2015-2-5
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?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by