我正在尝试将此功能从matlab
转换为C#
这些C#
陈述的等效matlab
是多少?下面的C#
部分显示了我不了解如何移植到matlab
C#
代码部分
res(res == 0) = p * scale * unit(res == 0);
W = min(unit, scale * p * (abs(res)).^ (-1));
整个matlab
部分,以及我尝试移植它
function W = huber(res, scale, param)
% function W = huber(res, scale, param)
%
% computes Huber's weight function for robust regression:
% min( 1, param/(|res|/scale) )
%
% arguments:
% res: vector of residuals
% scale: robust estimate of scale, such as MAD
% param: parameter of the Huber function; the
% default value is 2.5.
%
% returns:
% W: the vector of Huber weights
%
%
% P.B. Stark stark@stat.berkeley.edu
% 9 July 1997.
p = 2.5; % default parameter
if (nargin == 3),
if (param > 0),
p = param;
else
error('parameter must be positive')
end
end
unit = ones(size(res));
res(res == 0 ) = p*scale*unit(res==0);
W = min(unit, scale*p*(abs(res)).^(-1));
return;
C#代码。
public static double Hueber(double[] residuals, double scale, double param)
{
//Calculation of the mean estimate for a given range using Huber's weights
//The Huber's function is defined as min( 1, param/(|residuals|/scale))
//param: a given parameter - affects the range where weights = 1
//residuals: deviation from the mean estimate (I used the median as the first approximation)
//scale: estimate of variation. Some use 1.483*(median absolute deviation, or MAD,
// of the deviations of the data from their median). I used std, i.e. dblAveVar
//See http://www.stat.berkeley.edu/~stark/Preprints/Oersted/writeup.htm
double p = 2.5; //default parameter
if (param > 0)
p = param;
else
throw new Exception("parameter must be positive");
double[] unit = Ones(residuals.Length);
// What is the C# of this?
//res(res == 0) = p * scale * unit(res == 0);
//W = min(unit, scale * p * (abs(res)).^ (-1));
return W;
}
public static double[] Ones(int length)
{
double[] ones = new double[length];
ones.Populate(1.0);
return ones;
}
答案 0 :(得分:2)
//res(res == 0) = p * scale * unit(res == 0);
//W = min(unit, scale * p * (abs(res)).^ (-1));
代码如下;
public static double Hueber(double[] residuals, double scale, double param)
{
double p = 2.5; //default parameter
if (param > 0)
p = param;
else
throw new Exception("parameter must be positive");
for ( int i = 0; i < residuals.Length ; i++) {
if ( residuals[i] == 0) {
residuals[i] = p * scale * 1; // res(res == 0 ) = p*scale*unit(res==0)
}
// Then we can do smae step in this loop W = min(unit, scale*p*(abs(res)).^(-1))
residuals[i] = Math.Min(1, scale*p*Math.Abs(1/residuals[i]));
}
return residuals; // w = residuals[]
}