Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

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

Asked by ArashMat Fazl on 20 Dec 2011

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

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 :)

ArashMat Fazl

Tags

Products

1 Answer

Answer by Sean de Wolski on 20 Dec 2011
Accepted answer
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

Naz on 21 Dec 2011

@Walter. Good point

ArashMat Fazl on 21 Dec 2011

@Walter. Yup, it makes sense, even though down the road it creates some hassle.

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.

Sean de Wolski

Contact us