How do I calculate an infinite series using a function file with for-end loops?

2 views (last 30 days)
Given f(x)= [(x^2)/37]+[(x^3)/3!]+[(x^4)/4!]+[(x^5)/5!]+...
Using a function file (function fn=my_fun(x,n)) with for-end loops for several test files.
I'm just having issues defining the function file using the for-end loop. What I have so far is:
function [xval,nterms]=my_series(x,n)
  3 Comments
Walter Roberson
Walter Roberson on 3 Mar 2013
Could you confirm that the first term is divided by 37, and not factorial(2) as would match the 3! 4! 5! pattern?

Sign in to comment.

Accepted Answer

Youssef  Khmou
Youssef Khmou on 3 Mar 2013
hi gordon,
you function returns a scalar or vector values ? is this exp(x) Taylor series ?
you can try this light version :
function [xval]=your_series(x,n)
% X is vector input
% n number of iteration
xval=zeros(size(x));
order=0:n;
for ii=1:length(x)
for t=1:length(order)
xval(ii)=xval(ii)+(x(ii)^t)/factorial(t);
end
end
This function approximates well the EXP FUNCTION, replace the term ( x(ii)^t/t! ) with your general Formula .
  3 Comments
Youssef  Khmou
Youssef Khmou on 3 Mar 2013
Edited: Youssef Khmou on 3 Mar 2013
if it is a scalar then :
% given scalar x
S=0;
S=(x^2)/37;
for ii=3:N
S=S+((x^ii)/factorial(ii));
end

Sign in to comment.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 3 Mar 2013
x=2
n=5
f=x^2/37+sum(arrayfun(@(n) x^n/factorial(n),3:n))

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!