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
回答(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().
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!