Bamboo
Bamboo

Reputation: 973

Unexpected matlab behaviour when using vectorised assignment

I've come across some unexpected behaviour in matlab that I can't make sense of when performing vectorised assignment:

>> q=4;

>> q(q==[1,3,4,5,7,8])
The logical indices contain a true value outside of the array bounds.

>> q(q==[1,3,4,5,7,8])=1

q =

     4     0     1

Why does the command q(q==[1,3,4,5,7,8]) result in an error, but the command q(q==[1,3,4,5,7,8])=1 work? And how does it arrive at 4 0 1 being the output?

Upvotes: 4

Views: 544

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60564

The difference between q(i) and q(i)=a is that the former must produce the value of an array element; if i is out of bounds, MATLAB chooses to give an error rather than invent a value (good choice IMO). And the latter must write a value to an array element; if i is out of bounds, MATLAB chooses to extend the array so that it is large enough to be able to write to that location (this has also proven to be a good choice, it is useful and used extensively in code). Numeric arrays are extended by adding zeros.

In your specific case, q==[1,3,4,5,7,8] is the logical array [0,0,1,0,0,0]. This means that you are trying to index i=3. Since q has a single value, reading at index 3 is out of bounds, but we can write there. q is padded to size 3 by adding zeros, and then the value 1 is written to the third element.

Upvotes: 4

Related Questions