I have read this documentation on logical indexing, but it doesn't clarify my problem.
I have this line of code:
y = rand(20,3);
aa= unidrnd(2,20,3) - 1;
val = ( aa & y<1.366e-04) | (~aa & y<8.298e-04);
aa(val) = ~aa(val);
I cannot understand what is going on in the last line aa(val) = ~aa(val);
.
A similar question was asked here but it does not answer the question to the logical indexing specifically or what the logical values were implying.
when the code is run, val's
elements are zeroes.
Here's the tricky part, if I run only aa(val)
or ~aa(val)
I get Empty matrix: 0-by-1
. But if I run the entire line aa(val) = ~aa(val);
, i get a matrix aa
(with 0's and 1's, 20x3).
'~'
is performing the inversion of the values right? That means it should be assigning a matrix of 1's (20x3). But apparently it is not!!I
Can someone please breakdown to me what is happening in the last line.
If all of val
's elements are zeros (actually logical false
s or you would get an error), then indexing aa
by val
would return nothing (as you point out). So when you do the whole line
aa(val) = ~aa(val)
it is essentially assigning the inverse of nothing to nothing and hence it doesn't do anything and should return aa
unchanged. Remember that the ~
is being applied to aa(val)
and NOT to val
itself so it inverts the empty matrix aa(val)
and then assigns this to the empty matrix aa(val)
.