Replacement for for loop in matlab
Ältere Kommentare anzeigen
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
Antworten (1)
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().
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!