简体   繁体   English

在矩阵中查找最小非零值

[英]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., eg 我正在尝试找到一个二维数组,表示3d数组中第三维的最小值

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? 我想我可以对a的第三维进行排序,然后在1:depth-1中找到最小值 - 但这似乎不是最有效的方法吗?

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. 问题是a(a>0)返回一个线性数组,因此最终只有一个最小值,而不是具有最小值的2D数组。

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. 采用最小非零值的最安全方法是用Inf屏蔽它们,这样零点不会干扰最小值的计算。

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 例如,如果您知道任何元素都不会大于1000,那么您可以使用

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; 只需将值为零的那些点指定为无穷大,所以总是最小答案不会计为零......就像a(a == 0)= inf; %then count the min one minelement=min(a); %然后计算最小一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM