Help with matlab program for cos(x)

  • Thread starter Thread starter baznguy
  • Start date Start date
  • Tags Tags
    Matlab Program
Click For Summary
SUMMARY

The forum discussion centers on creating a MATLAB function named seriesCos to approximate the cosine function using a series expansion. The user encountered issues with the while loop not executing due to the initial error condition set for the variable er. The solution involves initializing er to a value greater than 1e-6 to ensure the loop runs correctly. Key MATLAB functions mentioned include factorial() and abs().

PREREQUISITES
  • Understanding of MATLAB programming and syntax
  • Familiarity with series expansions in mathematics
  • Knowledge of control flow structures, specifically while loops
  • Basic understanding of error tolerance in numerical methods
NEXT STEPS
  • Implement error handling in MATLAB functions
  • Explore MATLAB's built-in functions for numerical approximations
  • Learn about convergence criteria in series expansions
  • Study the use of recursion versus iteration in MATLAB
USEFUL FOR

Students learning MATLAB programming, educators teaching numerical methods, and anyone interested in implementing mathematical functions in MATLAB.

baznguy
Messages
1
Reaction score
0

Homework Statement



The function cos(x) can be approximated using the following series expansion:
1df491c1c760cda57c0f4f71cd2f191.png


Write a MATLAB function called seriesCos that takes a single scalar argument, x, uses the above formula to compute cos(x), and returns the result. Your function should use a while loop and continue adding terms to the series until the absolute value of the difference between successive iterations is less than 1.e-6. MATLAB functions that may prove useful include factorial() and abs().

Homework Equations


i can't get it to work and I'm not sure what I am doing wrong.It's not going through the loop or anything

The Attempt at a Solution


function y=seriesCos(x);
%calculate cos(x) through a series
%user call seriesCos(x,n)
%x is number to evaluate n is desire cycles through series
x=input ('Enter x to be evalute: ');
ser=1;
sum=0;
n=1;
er=0.0;
while er>=1e-6
an=(-1)^n*x^(2*n)/(factorial(2*n));
sum=ser;
ser=sum+an;
n=n+1;
er=abs((ser-sum)/(ser));
end
disp (ser)
disp (er)
 
Physics news on Phys.org
look at the line in which you start the while loop and you should see something wrong

what is er defined to be?
 
You are right, it's not going through the loop, because you are telling it not to:

Code:
er=0.0;
while er>=1e-6 
 ...

I suggest setting er to something larger than 1e-6 to start with :P
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
2
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 6 ·
Replies
6
Views
5K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K