使用NaN从多维数组中找出最小值 [英] Find out minimum value from a multidimensional array with NaNs

查看:76
本文介绍了使用NaN从多维数组中找出最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组(double[ , ]),我想找出最小值.我尝试使用Linq.Select.Min,但是由于我的数组通常包含NaN值,因此minvalue始终为NaN.

I have a bidimensional array ( double[ , ] ), and I want to find out what's the minimum. I tried Linq.Select.Min, but since my arrays typically contain NaN values, then minvalue is always NaN.

因此,我需要某种方法来找到跳过" NaN的最小值.

So, I need some way to find the Minimum value that "skips" the NaNs.

非常感谢您的帮助!

推荐答案

今天是扩展方法的一天!使用此功能可在所有double[,]上具有通用的Min()功能!

Today is the day for extension methods! Use this to have a generic Min() function on all your double[,]!

这里有一些通用的[,]扩展名.请注意,这仅适用于实现IComparable

Heres some generic [,] extensions. Please note this will only be available for types that implement IComparable

这个人什么都不会忽略:

This one ignores nothing:

public static T Min<T>(this T[,] arr) where T : IComparable
{
    bool minSet = false;
    T min = default(T);
    for (int i = 0; i < arr.GetLength(0); i++)
        for (int j = 0; j < arr.GetLength(1); j++)
            if (!minSet)
            {
                minSet = true;
                min = arr[i, j];
            }
            else if (arr[i, j].CompareTo(min) < 0)
                min = arr[i, j];
    return min;
}

这将让您指定一个要忽略的值,在特殊情况下,数组仅包含被忽略的值,它将返回被忽略的值.

This one will let you specify a value to ignore, and in the special case where the array only contains the ignored value, it will return the ignored value.

public static T Min<T>(this T[,] arr, T ignore) where T : IComparable
{
    bool minSet = false;
    T min = default(T);            
    for (int i = 0; i < arr.GetLength(0); i++)
        for (int j = 0; j < arr.GetLength(1); j++)
            if (arr[i, j].CompareTo(ignore) != 0)
                if (!minSet)
                {
                    minSet = true;
                    min = arr[i, j];
                }
                else if (arr[i, j].CompareTo(min) < 0)
                    min = arr[i, j];
    return (minSet) ? min : ignore;
}

以下代码的输出是

NaN
-10

NaN
-10

double[,] d = new double[5, 5]
{
    { 0, 1, 2, 3, 4 },
    { 5, 6, 7, 8, 9 },
    { 10, 11, -10, 12, 13 },
    { 14, 15, 16, 17, 18 },
    { 19, double.NaN, 21, 22, 23 }
};
Console.WriteLine(d.Min());
Console.WriteLine(d.Min(double.NaN));

这篇关于使用NaN从多维数组中找出最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆