Replacement for for loop in matlab

Uplim=input('Input the Upper limit:' );
Lowlim=input('Input the Lower limit: ');
sum=0;
for n=Lowlim:Uplim
wt=-2*pi:1e-3:2*pi;
f=(cos(n*wt))/((n^2)-1);
sum=sum+f;
end

Answers (1)

Jan
Jan on 30 May 2021
Edited: Jan on 30 May 2021
clear('sum') % Just to be sure, not for productive code
Lowlim = 2;
Uplim = 10;
% Cleaned loop:
S1 = 0;
wt = -2*pi:1e-3:2*pi;
for n = Lowlim:Uplim
S1 = S1 + cos(n * wt) / (n^2 - 1);
end
% Without a loop:
wt = -2*pi:1e-3:2*pi;
n = (Lowlim:Uplim).';
S2 = sum(cos(n .* wt) ./ (n .^ 2 - 1), 1);
isequal(S1, S2)
Hint: Do not use "sum" as name of the variable, bcause this causes conflicts with the built-in function sum().

Categories

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

Tags

Asked:

on 30 May 2021

Edited:

Jan
on 30 May 2021

Community Treasure Hunt

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

Start Hunting!