Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour for colon operator with arrays [duplicate]

I am looking into the code for an Octave function I found, and I found out a weird use of the colon operator. I could not find this behaviour explained in documentation or official MathWorks blogs (e.g. Colon Operator)

Suppose we have a couple of vectors:

>> a=[1,2,3]
a =
   1   2   3
>> b=[7,8,9]
b =
   7   8   9

Now if you use the colon operator you have:

>> a:b
ans =
   1   2   3   4   5   6   7

What I understood after several tries is that the above use is equivalent to:

>> a(1):b(1)
ans =
   1   2   3   4   5   6   7

Is my assumption correct?
Is there some documentation somewhere?

like image 668
Stefano Bossi Avatar asked Jul 29 '19 08:07

Stefano Bossi


1 Answers

It is actually documented in the official MATLAB documentation on colon:

j — Beginning operand
real scalar
Beginning operand, specified as a real scalar integer-valued fi object or built-in numeric type.

If you specify non-scalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).

So yes, it indeed does what you mention it does for array syntax, take the first element of the vector.

Octave follows this implementation, see the official source code (thanks to Andy for finding this)

like image 108
Adriaan Avatar answered Oct 07 '22 03:10

Adriaan