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

I searched for the most efficient way to find the zero minimum of the matrix and found this on the forum:

Let the data be a matrix A

 A(~A) = nan; minNonZero = min(A); 

This is very short and efficient (at least the number of lines of code), but I don’t understand what happens when we do this. I can not find any documentation about this, since this is not an operation on matrices like + , - , \ , ... will be.

Can someone explain to me or give me a link or something that could help me understand what has been done? Thanks!

+6
source share
2 answers

It uses logical indexing.

~ in Matlab is not an operator. When used in a double array, it finds all elements equal to zero. eg:.

 ~[0 3 4 0] 

Results in a logical matrix

 [1 0 0 1] 

i.e. this is a quick way to find all the null 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 affect only elements that are true, so in this case elements 1 and element 4.

Finally, A(~A) = NaN will replace all elements from A that are 0 with NaN , which min ignores and therefore you will find the smallest nonzero element.

+9
source

The code you provided is:

 A(~A) = NaN; minNonZero = min(A); 

Is the following done:

  • Create logical index
  • Apply logical index to A
  • Change A by Assigning NaN Values
  • Get the minimum of all values, not including NaN values

Please note that this leaves you with a modified A , which may be undesirable. But more importantly, it has some drawbacks, because you spend time changing A and, possibly, even getting a minimal large matrix. Therefore, you can speed things up (and even reduce one line) by doing the following:

  minNonZero = min(A(logical(A))) 

Basically, you now skipped step 3 and possibly reduced step 4.

In addition, you seem to get additional slight acceleration:

  minNonZero = min(A(A~=0)) 

I have no good reason for this, but it seems that step 1 is now done more efficiently.

+3
source

Source: https://habr.com/ru/post/951213/


All Articles