What does the command A(~A) really do in matlab

matlab

Solution

It uses logical indexing

`~` in Matlab is the not operator. When used on a double array, it finds all elements equal to zero. e.g.:

~[0 3 4 0]

Results in the logical matrix

[1 0 0 1]

i.e. it's a quick way to find all the zero elements

So if `A` = `[0 3 4 0]` then `~A` = `[1 0 0 1]` so now `A(~A)` = `A([1 0 0 1])`. `A([1 0 0 1])` uses logical indexing to only affect the elements that are true so in this case element 1 and element 4.

Finally `A(~A) = NaN` will replace all the elements in A that were equal to `0` with `NaN` which `min` ignores and thus you find the smallest non-zero element.

Problem

I was looking to find the most efficient way to find the non zero minimum of a matrix and found this on a forum : Let the data be a matrix `A`. ``` A(~A) = nan; minNonZero = min(A); ``` This is very short and efficient (at least in number of code lines) but I don't understand what happens when we do this. I can't find any documentation about this since it's not an `operation` on matrices like `+`,`-`,`\`,... would be. Could anyone explain me or give me a link or something that could help me understand what is done ? Thank you !

Original source