@WeatherVane and @TroyHaskin have an answer for your question in the comments: You are likely not correctly iterating through your array, so your vector calculation in C is probably not what you want it to be. (We can only assume that your Matlab implementation is correct.)
In C, array indexes start at 0, not at 1. We can only assume that M
is the number of elements in the array x
and that you really wanted to include all M
elements in your for
loop. So the elements of x
range from x[0]
through x[M-1]
. In your code, you are not including the first element x[0]
in your calculation. Try this instead:
double sumVector(double x[], int M) {
double y = 0.0;
int i;
for(i=0; i<M; i++){
y += 0.5*x[i] + x[i]*x[i]*cos(floor(x[i]/4.0) - 32.0));
}
return y;
}
Notice that I have changed the type of your x
to an array of double
. In Matlab, double
is the default precision of floating point numbers. Think as if the same were true for C: use double
unless you really know what you're doing.
This i=0; i<MAX; i++
format is common practice in C. Get used to it. It should look weird to start at i=1
or to test for i<=MAX
. (It doesn't mean it's necessarily wrong, but it should catch the eye.)
Also, @Olaf's comment warns you to be careful about division in C. If both operands are of an integer type, it will perform integer division. If you use, for example, 1.0 instead of 1, it forces floating-point division. It also makes it more clear to the human reader that you are using floating point constants instead of integer constants.
In Matlab, cos
accepts radians and the C library cos()
also uses radians.