-5
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 have this code. Can any one explain to me what is happening here. I have tried to understand it step by step (debugging) but I cannot understand the purpose of using inverse '~' in line 4 and also using 'val' as indices.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
nashynash
  • 375
  • 2
  • 19
  • I assume you did not write this code yourself since you asked this question, thus I suggest you ask the one that actually did write it to explain you their code. – Adriaan Oct 12 '15 at 10:52

1 Answers1

4
y = rand(20,3); 

Creates a matrix of uniformly distributed random numbers, y.

aa= unidrnd(2,20,3) - 1;

Creates a matrix of uniformly distributed random integers, that goes from 1 to 2, and then subtract one. Thus, aa is a matrix of 0s and 1s.

val = ( aa & y<1.366e-04) | (~aa & y<8.298e-04);

This line checks all the values where aa is 1AND y<1.366e-04 OR aa is 0 AND y<8.298e-04. Note that this barely happens, being y uniformly distributed numbers from 0 to 1, being them this smalls is unlikely.

aa(val) = ~aa(val);

Take all those cases computed before, and make aa change from 0 to 1 or from 1 to 0 if it happened in that index.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
  • So that means, 'aa' will remain as 'aa' since `y<1.366e-04` and `y<8.298e-04` will never be satisfied. – nashynash Oct 12 '15 at 09:52
  • @nashynash Yes, but careful, they can be satisfied. There is a probability of `p=8.298e-04` of one of them to be satisfied. – Ander Biguri Oct 12 '15 at 09:54
  • okay. I have one more doubt as to how MatLAB takes the values of `aa(val) = ~aa(val);`. I tried looking for documentation on this method of assignment but I cannot find it. – nashynash Oct 12 '15 at 09:57
  • @nashynash ? That is standard Matlab indexing.... Read: https://stackoverflow.com/questions/32379805/linear-indexing-logical-indexing-and-all-that – Ander Biguri Oct 12 '15 at 09:58
  • okay I will read that. I forgot to mention that `'val'` elements are always `'0'` since the conditions are never satisfied. What does that imply to the assignment in line 4. – nashynash Oct 12 '15 at 10:07
  • @nashynash Read logical indexing from the post I gave you. Or try `~aa(val)` by yourself – Ander Biguri Oct 12 '15 at 10:08