Why Matlab indexing for Matrices is not the same as that of Vectors?
Show older comments
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
Jan
on 20 Dec 2011
Btw.: You do not need square brackets around a vector: "[1:5]" is slower than "1:5".
Robert Cumming
on 21 Dec 2011
is it slower - its not for me (Windows R2009b) - is this true for newer releases?
Sean de Wolski
on 21 Dec 2011
In theory the overhead of the call to horzcat() slows it down. I'm not able to reproduce this on R2011b 64bit, though:
t1 = 0;
t2 = 0;
for ii = 1:5000000
tic
x = 1:2;
t1 = t1+toc;
tic
y = [1:2];
t2 = t2+toc;
end
disp([t1 t2]);
5.6346 5.5493
Robert Cumming
on 21 Dec 2011
I have heard before that it slows it down - but never been able to reproduce it either -
your test on my PC produces: 3.2038 3.2034
Sean de Wolski
on 21 Dec 2011
Four 10000ths of a second difference!! Not too shabby after five million iterations.
Robert Cumming
on 21 Dec 2011
indeed :)
Accepted Answer
More Answers (0)
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!