Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

Converting Matlab to C

3 visualizzazioni (ultimi 30 giorni)
Alex
Alex il 12 Ago 2011
Chiuso: MATLAB Answer Bot il 20 Ago 2021
So I have solved a problem in matlab and it works brilliantly. However my boss requires the method in C. I am doing a least squares minimization using fminsearch. I am trying to replicate the function being solved for in C (I already have the neldermead function in C) My matlab function to be solved is:
function sse=myfit(params,Input,Actual_Output)
global c
a=params(1);
b=params(2);
x = (exp(a*2*pi)-cosh(a*b*Actual_Output))/sinh(a*b*Actual_Output);
c = -1/atanh(x);
Fitted_Curve = (1/(a*b))*(c-asinh(sinh(c)*exp(a*Input*2*pi)));
Error_Vector=Actual_Output-Fitted_Curve ;
sse=sum(Error_Vector.^2);
And this is what I am trying to replicate in C:
static double function(int n, double x[])
{
double c, x_coeff;
double Fitted_Curve[5];
double Error_Vector[5];
int i;
double Actual_Output[5]={1.2, 2.693, 4.325, 6.131, 8.125};
double Input[5]={1, 2, 3, 4, 5};
double sum = 0;
x_coeff = (exp(x[0]*2*pi)-cosh(x[0]*x[1]*Actual_Output[0]))/(sinh(x[0]*x[1]*Actual_Output[0]));
c = (-1)/(atanh(x_coeff));
for (i = 0; i <= 4; i++)
{
x_coeff[i] = (exp(x[0]*2*pi)-cosh(x[0]*x[1]*Actual_Output[0]))/(sinh(x[0]*x[1]*Actual_Output[0]));
c[i] = (-1)/(atanh(x_coeff[i]));
Fitted_Curve[i] = (1/(x[0]*x[1]))*(c[i]-asinh(sinh(c[i])*exp(x[0]*Input[i]*2*pi)));
Error_Vector[i] = Actual_Output[i]-Fitted_Curve[i];
printf(" x_coeff(%d) = %f %f\n", i, x_coeff[i], c[i]);
}
for (i = 0; i <= 4; i++)
{
sum = sum + Error_Vector[i]*Error_Vector[i];
}
return sum;
}
It doesnt give the same answer (atanh(x>1) = inf) which obviously suggests they are not doing the same thing. Can anyone see where I have gone wrong?
Thanks

Risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by