Nested For loop problem
1 view (last 30 days)
Show older comments
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 Comment
Chaowei Chen
on 21 Aug 2011
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.
Accepted Answer
Oleg Komarov
on 21 Aug 2011
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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!