1
我試圖從matlab
此功能轉換爲C#
從MATLAB轉換的代碼段爲C#
什麼是這些matlab
語句相當於C#
?下面的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 [email protected]
% 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;
}
如果您說出代碼應該做什麼會更容易。 – HimBromBeere
Btw你的默認參數值沒有用處。 'p'的值總是被'param'覆蓋或者拋出一個異常,而原始代碼中沒有這樣的情況,它具有基於'nargin'的值的額外檢查(這裏不存在) – pinkfloydx33
從複習matlab docs'res(res == 0)= X'表示將res的索引值爲零的res的所有索引設置爲X.因此,通過res進行迭代,如果值爲零,則將值替換爲公式在右邊。單元(res == 0)表示res中相應索引值爲零的單元索引。 **我認爲**。除了快速查看他們的文檔外,我對Matlab一無所知。你必須知道matlab如何處理乘法向量並獲取絕對值。最終,我認爲這將是一個非常迭代的解決方案。 – pinkfloydx33