Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Converting Matlab to C Code

조회 수: 1 (최근 30일)
Alex
Alex 2011년 8월 16일
마감: MATLAB Answer Bot 2021년 8월 20일
The following code is the Matlab version which works perfectly:
Starting=[1 1 -1];
options=optimset('Display','iter');
Estimates=fminsearch(@myfit,Starting,options,t_d,Data)
function sse=myfit(params,Input,Actual_Output)
a=params(1);
b=params(2);
c=params(3);
Calling the Function:
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);
I have tried to replicate the function in C which looks like this:
static double function(int n, double x[])
{
double c;
double Fitted_Curve[5];
double Error_Vector[5];
int i;
double a, b, sum = 0;
double v1[5], v2[5], geom_inv[5], norm = 0, norm_2 = 0, v2sum = 0, x_coeff = 0;
// Actual_Output[5] = {1.2, 2.693, 4.325, 6.131, 8.125};
a = x[0];
b=x[1];
c=x[2];
for (i = 0; i <= 4; i++)
{
Fitted_Curve[i] = (1/(a*b))*(c-asinh(sinh(c)*exp(a*Input[i]*2*pi)));
Error_Vector[i] = Actual_Output[i]-Fitted_Curve[i];
}
for (i = 0; i <= 4; i++)
{
sum = sum + Error_Vector[i]*Error_Vector[i];
}
printf("sum = %f\n", sum);
a_global = a;
b_global = b;
// x_coeff_global = x_coeff;
return sum;
}
It runs but doesnt get the same result as the Matlab. The matlab is right, I know that, but the C doesnt get close enough

답변 (1개)

Walter Roberson
Walter Roberson 2011년 8월 16일
Your MATLAB code is not right. We discussed this before here. You have too many inputs to "myfit"
  댓글 수: 1
Alex
Alex 2011년 8월 16일
The Matlab works and it produces the correct values to 3dp. I'm not sure what you are spotting that I am not but I think you may be getting confused with the fact that it is sent first to the function fminsearch which then send myfit the correct information, because it works

Community Treasure Hunt

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

Start Hunting!

Translated by