/// <summary>
/// 范数
/// 向量:L0,L1,L2,LP=>[Σ(|x[i]|^p)]^(1/p);P_INF=>max|x[i],|M_INF=>min|x[i]
/// 矩阵:L1=>max,colΣ(|x[i,j]|);INF=>max,rowΣ(|x[i,j]|);F=>[Σ[(x[i,j])^2]]^0.5;L2=>[λmax(X'X)]^0.5
/// </summary>
/// <param name="Datas"></param>
/// <param name="Type">范数类型</param>
/// <param name="P">|x[i,j]|^P</param>
/// <returns></returns>
public static double Norm(double[,] MatrixEin,NormType type,double P=0 )
{
double norm = double.MinValue;
int Row = MatrixEin.GetLength(0);
int Col = MatrixEin.GetLength(1);
if (Row * Col == Row || Row * Col == Col)
{
double[] data = MatrixGetVector(MatrixEin, 0, Col > Row);
switch (type)
{
case NormType.L0:
{
norm = data.ToList().Count<double>(x => x != 0);
break;
}
case NormType.L1:
{
norm = data.Sum<double>(x => Math.Abs(x));
break;
}
case NormType.L2:
{
norm = Math.Sqrt(data.Sum<double>(x => x * x));
break;
}
case NormType.LP:
{
norm = Math.Pow(data.Sum<double>(x => Math.Pow(Math.Abs(x),P)),1.0/(double)P);
break;
}
case NormType.P_INF:
{
norm=data.Max(x=> Math.Abs(x));
break;
}
case NormType.M_INF:
{
norm = data.Min(x => Math.Abs(x));
break;
}
}
}
else
{
switch (type)
{
case NormType.L1:
//列元素绝对值和的最大值
{
for (int i = 0; i < Col; i++)
{
norm = Math.Max(norm, MatrixGetVector(MatrixEin, i, false).Sum(x => Math.Abs(x)));
}
break;
}
case NormType.INF:
//行元素绝对值和的最大值
{
for(int i = 0; i < Row; i++)
{
norm = Math.Max(norm, MatrixGetVector(MatrixEin, i, true).Sum(x => Math.Abs(x)));
}
break;
}
case NormType.F:
//[Σ(xi^2)]^0.5
{
norm = 0;
for(int i = 0; i < Row; i++)
{
norm += MatrixGetVector(MatrixEin, i, true).Sum(x => x * x);
}
norm = Math.Sqrt(norm);
break;
}
case NormType.L2:
//λmax(ATA)^0.5
{
double[,] nnd = Transpose(MatrixEin);
nnd = MultiplyMatrix(nnd, MatrixEin);
double lambda = MatrixEigenvalue(nnd, ref nnd,Type:0);
norm = Math.Sqrt(lambda);
break;
}
}
}
return norm;
}
范数(Norm)代码(c#)
猜你喜欢
转载自blog.csdn.net/JAYLEE900/article/details/131987792
今日推荐
周排行