I'm trying to find a 2d array that represents the minimum values of the 3rd dimension in a 3d array., eg
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?
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);
One possibility would be to simply make all the zero values very big.
For example, if you know that no elements would ever be larger than 1000 you could use
b = min(a+1000*(a==0),[],3)
simply assign those points infinity where the value is zero so always the min answer will not count zero ones..... like a(a==0)=inf; %then count the min one minelement=min(a);
remove zero elements from matrix like this:
a = [10 2 0 4 5; 156 1.7 45 23 0 ];
a(a == 0) = NaN;% not a number
min(a(:))
>> ans = 1.7
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.