% A simple function to demonstrate different ways to write a loop statement
% We 
clear

x=input('enter x: ');
N=input('enter N: ');

% Our first method is to introduce an array that contains all the
% individual terms in the sum, and then sum over all the terms:
u = zeros(N,1);
for n=1:N
    u(n) = (-1)^(n+1)/n*sin(n*x);
end
sum1 = sum(u);

% Our second method is the classic way to add a term to a variable called
% sum2 in a loop:
sum2 = 0;
for n=1:N
    sum2 = sum2 + (-1)^(n+1)/n*sin(n*x);
end

% Our third method is to take advantage of the matrix operations in MATLAB:
nv = 1:N;
v = (-1).^(nv+1)./nv.*sin(nv*x);
sum3 = sum(v);

fprintf('sum 1 is %8.6f,  sum 2 is %8.6f,  sum 3 is %8.6f\n',sum1,sum2,sum3);

