Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the minimum non zero value in a matrix

I'm trying to find a 2d array that represents the minimum values of the 3rd dimension in a 3d array., e.g.

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 that isn't correct? I guess I could sort the third dimension of a and then find the minimum within 1:depth-1 - but that doesn't seem the most efficient way?

Any thoughts?

like image 303
trican Avatar asked Jun 27 '12 19:06

trican


1 Answers

The problem is that a(a>0) returns a linear array, so you'll end up with one minimum, as opposed to a 2D array with minima.

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

tmp = a;
tmp(tmp==0) = Inf;

b = min(tmp,[],3);
like image 63
Jonas Avatar answered Sep 18 '22 17:09

Jonas