We’d love to hear any feedback or comment from you!

###### Engineering · Computer Science
Question details

Example 2.2: Nested Loops
% Example_2_2.m
% This program illustrates the use of nested loops, i.e.
% an inner 'for' loop inside an outer 'for' loop.
% The program calculates e^x by both MATLAB's 'exp'
% command (variable 'ex2'), and by a Taylor series
% expansion (variable 'ex1'), where -0.5 < x < 0.5.
% The outer 'for' loop is used to determine the x
% values. The inner loop is used to determine the Taylor
% series method for evaluating e^x. In this example,
% term(n+1) is obtained by multiplying term(n) by x/n.
% The variable 'term' is established as a vector so that
% MATLAB's built-in 'sum' function can be used to sum
% all the terms calculated in the Taylor series method.
% A maximum of fifty terms is used in the series.
% Program output is sent both to the screen and to a
% file. By printing the output to a file, you can easily
% edit the output file to line up column headings,
% etc. (which you can't do when printing to the screen).
% Note: e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...
clear; clc;
xmin=-0.5; dx=0.1;
fo=fopen('output.txt','w');
fprintf(' x ex1 ex2 ');
fprintf('------------------------------------- ');
fprintf(fo,' x ex1 ex2 ');
fprintf(fo,'------------------------------------- ');
for i=1:11
x=xmin+(i-1)*dx;
ex2=exp(x);
term(1)=1.0;
for n=1:49
term(n+1)=term(n)*x/n;
if abs(term(n+1)) <= 1.0e-7
break;
end
end
ex1 = sum(term);
fprintf('%5.2f %10.5f %10.5f ',x,ex1,ex2);
fprintf(fo,'%5.2f %10.5f %10.5f ',x,ex1,ex2);
end
fclose(fo);
------------------------------------------------------------