954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Matlab cosine user defined function?

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?

Panathinaikos22
Junior Poster
135 posts since Aug 2011
Reputation Points: -4
Solved Threads: 6
 

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?

Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

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

Panathinaikos22
Junior Poster
135 posts since Aug 2011
Reputation Points: -4
Solved Threads: 6
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You