0

I am not a very frequent Matlab user. So today, when I got the message "Subscript indices must either be real positive integers or logicals." it got me wondering. What would happen if I did

x = [1 2 3];
x(true)
x(false)

My guess would have been that false is treated as 0 and true as 1, so the x(true) should have returned the first element, which it did, while x(false) should have returned an error. It didn't. x(false) apparently returns an empty array. Why?

I couldn't find any reference about this rather odd behaviour, that's why I'm asking here, sorry if it's a duplicate or some normal behaviour I should know about.

buzjwa
  • 2,632
  • 2
  • 24
  • 37
Nico
  • 574
  • 1
  • 4
  • 19
  • Matlab is and interpreted language, it will not surprise me if it treat true as 1 and false as 0. Have you tried it? Remember that the matlab arrays starts from 1 (not from 0 as in C) – Niles Jun 16 '16 at 09:49
  • That's not it. I found the answer, I will post it. – Nico Jun 16 '16 at 09:50
  • 3
    There is a very nice Q&A by @LuisMendo over [here](http://stackoverflow.com/questions/32379805/linear-indexing-logical-indexing-and-all-that) about all possible ways of indexing in MATLAB – BillBokeey Jun 16 '16 at 09:54

1 Answers1

4

Matab is quite odd, but in this context is a very neat feature.

If you have x = [1 2 3];, you can access with a logical with corresponding length:

  • x([false false true]) is equivalent to x(3)
  • x([false false false]) is equivalent to x([])
  • x([false true true]) is equivalent to x([2 3])

etc.

This is useful for preparing a logical array which contains information about each array position and this one is considered or not according to the logical state.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • Yup, this is it. Thank you! Also something funny about this is that `x([true true true true])` throws an error (which is logical since we're trying to access the 4th element of an 3-element array) but `x([true true true false])` doesn't. – Nico Jun 16 '16 at 09:54
  • x([true true true false]) is ok because Matlab don't make any check until running the code, so in runtime you are not accessing the forth element of the array. Tank to glglgl for the nice answer – Niles Jun 16 '16 at 10:09
  • 2
    _with corresponding length_ Not necessarily. Try `x([false true])` or `x([false false true false])` :-) – Luis Mendo Jun 16 '16 at 10:21