Why Matlab indexing for Matrices is not the same as that of Vectors?

1 view (last 30 days)
Hi, I wonder why indexing is setup differently for matrices versus vectors ? If A is a matrix, A(B) has the same size of B. But if A is vector and B also a vector, A(B) will be a column or row vector depending on A and not on B. As an example:
>A=magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
> A([1:5]')
ans =
16
5
9
4
2
> A([1:5])
ans =
16 5 9 4 2
> A=ones(1,10);
> A([1:5])
ans =
1 1 1 1 1
> A([1:5]')
ans =
1 1 1 1 1
As you see , if A is a matrix, A([1:5]) is a row vector and A([1:5]') is a column vector. But if A is a row vector, A([1:5]) and A([1:5]') have the same size and both a row vector.
This double standard in treating a Matrix and a Vector produces special cases in the code that you have to correct to avoid error messages.
Why?
-Arash
  6 Comments
Sean de Wolski
Sean de Wolski on 21 Dec 2011
Four 10000ths of a second difference!! Not too shabby after five million iterations.

Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 20 Dec 2011
docsearch linear indexing
Gives a good set of explanations. The only time a row vector is returned from a linear index column vector (as in your example above) is when A is a row vector
  5 Comments
ArashMat Fazl
ArashMat Fazl on 21 Dec 2011
@Walter. Yup, it makes sense, even though down the road it creates some hassle.
Sean de Wolski
Sean de Wolski on 21 Dec 2011
It can be a hassle occasionally (especially when find() returns a column vector). I usually just force everything to column vectors using the colon operator (x(:)) if there's any quuestion.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!