Nested For loop problem

조회 수: 1 (최근 30일)
Pratap Bhanu Solanki
Pratap Bhanu Solanki 2011년 8월 21일
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
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
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.
  댓글 수: 1
Pratap Bhanu Solanki
Pratap Bhanu Solanki 2011년 8월 22일
Thanks,
It really worked.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by