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

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

hi is the code below fine? i mean your input is : vector X and order N , so as for every point in X we sum N terms defined with general formula .
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

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

Function returns scalar quantity.
This is very helpful in the general procedure, but in defining the xval(ii)=... term, I'm not sure how to replace it with my formula, which has the first term divided by 37, not factorial(2). How do I generalize this formula and input it in the for-end loop for calculation?
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.

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!