MATLAB: Exponential Function using Taylor series

exponentialinputMATLABoutputscripttaylor serieswhile loop

Hi, I've been trying to write a code which has a row vector input of numbers (x in my code) and the output is row vector e^x (y in my code). e^x is given by the sum of: x^n/n! where n=0,1,2… I have to try and write an unbounded while loop with these conditions: n has a maximum of 50 and that y is more than 0.001 (if less than 0.001, sequence is terminated).
This is what I've done:
the problem is:
1)i've written a loop for the factorial function in a different script, how do i input that into this one?
2)my output is still less than 0.001 when it shouldn't have happened. when given this row vector: [-2 -1.5 -1] the output should be [0.1365 0.2232 0.3679] but I do not obtain these numbers. 🙁
Any help would be amazing! thanks 🙂

Best Answer

  • 1) You need to turn your factorial script into a function. However, note that MATLAB has a function called factorial already. So either use MATLAB's function, or name your function something else (e.g., make a file called myfactorial.m and fill in the code).
    2) Your while loop is flawed if x is a vector, since the if-test is not doing what you think it is. Put a for-loop around that while loop and loop through all the elements of x. E.g., if this outer loop is for k=1:numel(x), then use x(k) in the while loop instead of just x. E.g.,
    x = input(etc)
    e = zeros(size(x)); % your result vector, see (3) below
    for k=1:numel(x)
    n = 0;
    while( use x(k) here instead of just x )
    3) You are not summing the terms! You compute a term as y, then you throw it away and overwrite it on the next iteration with another term. So start with a result vector, e.g. e = zeros(size(x)), then in your loop have e(k) = e(k) + y;