Nested For loop problem
1 回表示 (過去 30 日間)
古いコメントを表示
Hello all, I am surprised by the thing which is happening to me today. As the following part of code I am using nested for loop.The thing which is troubling me that while running the value of variable Sum_error reaches to the order of 1e27.
Sum_err=0;
last_sum=0;
for k = 1:4;
clear Sum_err;
Sum_err=0;
for n=1:2001
Env(n)=Peak*exp(-(Ts(n)-Tp)/Tau(k));
if (Env(n)<=AMt(n))
Env(n)=AMt(n);
Peak=AMt(n);
Tp=Ts(n);
end
Sum_err=Sum_err+(Envelope(n)-Env(n))^2;
end
MSE(k)=Sum_err/2001;
end
but when I iterate outer loop just once then the true value(which is expected logically) of Sum_err and MSE come likethis :
Sum_err=0;
last_sum=0;
for k = 5;
clear Sum_err;
Sum_err=0;
for n=1:2001
Env(n)=Peak*exp(-(Ts(n)-Tp)/Tau(k));
if (Env(n)<=AMt(n))
Env(n)=AMt(n);
Peak=AMt(n);
Tp=Ts(n);
end
Sum_err=Sum_err+(Envelope(n)-Env(n))^2;
end
MSE(k)=Sum_err/2001;
end
Please answer this soon as you figure it out. I will be really grateful to you.
Moreover the full code is here for the sake of completeness.
%Matlab Assignment_1
%Code for simulation of envelope detection
clc;
clear all;
close all;
%AM signal Generation
Ka=.5;
Tm = 5e-4;
%Time period of message signal
Ts =[0:Tm/1000:2*Tm];
%Simulation time
Mt = cos(4000*pi*Ts);
%plot(Ts,Mt);
Ct = cos(80000*pi*Ts);
%plot(Ts,Ct);
Envelope=(Ka*Mt+1);
AMt = (Ka*Mt+1).*Ct;
%plot(Ts,AMt);
Tau = [2.5:.5:50]*1e-5; %96 values
MSE = zeros(1,96);
%Envelope detection
%Tau=1e-4;
Env=zeros(1,2001);
Peak=0.0000;
Tp=0.0000;
Sum_err=0;
last_sum=0;
for k = 1:4;
clear Sum_err;
Sum_err=0;
for n=1:2001
Env(n)=Peak*exp(-(Ts(n)-Tp)/Tau(k));
if (Env(n)<=AMt(n))
Env(n)=AMt(n);
Peak=AMt(n);
Tp=Ts(n);
end
Sum_err=Sum_err+(Envelope(n)-Env(n))^2;
end
MSE(k)=Sum_err/2001;
end
hold on;
plot(Tau,MSE);
%plot(Ts,Env,'color','red');
1 件のコメント
Chaowei Chen
2011 年 8 月 21 日
I don't exactly understand what is your question,
from your code,
for k = 1:4;
clear Sum_err;
Sum_err=0;
...
end
It is expected that Sum_err is of course zero.
採用された回答
Oleg Komarov
2011 年 8 月 21 日
You don't need the clear:
clear Sum_err;
Sum_err = 0;
Reinitialize Tp and Peak as well:
for k = 1:...
Sum_err = 0;
Tp = 0;
Peak = 0;
...
You also don't need to declare them outside of the loop.
その他の回答 (0 件)
参考
カテゴリ
Help Center および 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!