Hello, im trying to create a cos function in MATLAB, but it is wrong. :/

well from Taylor serie we have

cosx = 1 - x^2/2! + x^4/4! - x^6/6! +... + x^n/n!

or for noobs ->

cosx = x^1/1! - x^2/2! + x^4/4! - x^6/6! +... + x^n/n!

this is my code in MATLAB

function y = cosine(x,n)
sum = x;
term = x;
for i = 1:2:n %with step 2
      temp = -temp * (x^i/i);
      sum = sum + temp;
end
y = sum;

I try this also

function y = cosine(x,n)
sum = x;
term = x;
for i = 1:2:n %with step 2
      temp = -temp * x *x /(i*(i+1)); 
      sum = sum + temp;
end
y = sum;

Any help how i can fix term?

You are adding it wrong... I can't remember whether Matlab has a built-in function for factorial. If not, you need to implement it yourself. Shouldn't be that difficult.

Actually x^1/1! is not always equal to 1. If it is wrong, you may need to do it differently as...

Let see if this is what should be like...

sum = 1;
temp = -1;
for i = 2:2:n %with step 2
      sum += temp * ((x^i)/fact(i));
      temp = -temp;
end

PS: Your code starts the value of "i" with 1 and step up 2, so the values used in the function are 1, 3, 5, ...
PSS: The value "n" in your function is still unclear to me. Is it the maximum it should go or it is else?

You are adding it wrong... I can't remember whether Matlab has a built-in function for factorial. If not, you need to implement it yourself. Shouldn't be that difficult.

Actually x^1/1! is not always equal to 1. If it is wrong, you may need to do it differently as...

Let see if this is what should be like...

sum = 1;
temp = -1;
for i = 2:2:n %with step 2
      sum += temp * ((x^i)/fact(i));
      temp = -temp;
end

PS: Your code starts the value of "i" with 1 and step up 2, so the values used in the function are 1, 3, 5, ...
PSS: The value "n" in your function is still unclear to me. Is it the maximum it should go or it is else?

Founded

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.