Find the minimum non-zero value in the matrix

I am trying to find a 2d array that represents the minimum values ​​of the 3rd dimension in a 3d array. For example,

a = floor(rand(10,10,3).*100); % representative structure b = min(a,[],3); % this finds the minimum but also includes 0 

I tried using:

 min(a(a>0),3) 

but is it wrong? I guess I could sort the third dimension of a, and then find the minimum within 1: depth-1 - but this does not seem to be the most efficient way?

Any thoughts?

+8
multidimensional-array matlab
source share
4 answers

The problem is that a(a>0) returns a linear array, so you get one minimum, not a two-dimensional array with minima.

The safest way to take a minimum of non-zero values ​​is to mask them with Inf , so the zeros do not interfere with the calculation of the minimum.

 tmp = a; tmp(tmp==0) = Inf; b = min(tmp,[],3); 
+7
source share

One possibility would be to simply make all zero values ​​very large.

For example, if you know that no item will ever be greater than 1000, you can use

 b = min(a+1000*(a==0),[],3) 
+3
source share

just assign these infinity points where the value is zero, so always the minimum answer will not count zero. a (a == 0) = inf; % then count min. minelement = min (a);

0
source share

remove the null elements from the matrix as follows:

  a = [10 2 0 4 5; 156 1.7 45 23 0 ]; a(a == 0) = NaN;% not a number min(a(:)) >> ans = 1.7 
0
source share

All Articles