Search code examples
arraysmatlabmatrix-indexing

Square brackets operator in Matlab without comma between its two values


I'm having a hard time figuring out what this code does, because googling square brackets doesn't yield appropriate results for the way the search engine works.

id2 is a 1x265 array (so basically a 1d vector with 265 values)

m is a 1x245 array (so basically a 1d vector with 245 values)

id2 = id2([m m(end)+1]);

For what I've seen so far, there always is a comma between the first and second value in the square brackets.

If it was

id2 = id2[m, m(end)+1]

In my little Matlab experience I would have known its meaning but this is not the case, never seen this one before.

The square brackets are also enclosed in brackets ( ) after id2 so this makes me think that

id2 = id2([m m(end)+1]) and id2 = id2[m, m(end)+1] are two completely different things.

Can you explain me what that code does please?


Solution

  • [1, 2] and [1 2] are equivalent. Either a comma or a space can denote element separation when building arrays using square brackets.
    Indexing, using parentheses (), has to be done using commas: A(3,1), not A(3 1). The same holds for argument lists in functions: mean(A,[],1) needs commas to separate the various parameters.

    id2 = id2([m m(end)+1]); should then be clear: you build an array [m m(end)+1], i.e. you take m and add one extra element, m(end)+1, to its end. These should be integers, presumably, since the look like they are indexing into id2. Given the above, id2 = id2([m, m(end)+1]); is exactly equivalent.

    I can recommend reading this post on the various ways of indexing in MATLAB.