Clear Filters
Clear Filters

While loop not working as expected

1 view (last 30 days)
Arquelau
Arquelau on 5 Nov 2016
Answered: Image Analyst on 5 Nov 2016
So, I am trying to calculate the amplitude of a rectangular signal that causes its energy to be 1. From theory, I've come to the answer that A = 1/sqrt(Tp), where A is the amplitude and Tp is the time of existence of the signal. In this case, Tp=25, so I am expecting A to be 0.2, however, my while loop always does one more iteration than what I am expecting. Below is my code:
periodo = 0.0001;
t = 0:periodo:25;
Tp = 25;
rect = @(x) 0.5*(sign(x+0.5) - sign(x-0.5)); % definição da função rect()
A=0;
x = A*rect((t-Tp/2)/Tp);
q = trapz(x.^2)*periodo;
while (q<1)
A = A + 0.1;
x = A*rect((t-Tp/2)/Tp);
q = trapz(x.^2)*periodo;
end
fprintf('%f and %f', q, A);
What I get is A = 0.3, as if the expression being tested in the while loop was (q<=1), instead of (q<1), and I really dont understand why. If I reverse it, that is, if I start with A=10 and subtract A in each iteration, it works fine, giving me A = 0.2, but I dont want to use this approach.
Am I missing something? Many thanks!

Answers (1)

Image Analyst
Image Analyst on 5 Nov 2016
You're doing it while q < 1. But when you get to a situation where q >= 1, it quits the loop. However, you're left with the values that are too big. You need to index the numbers and then when you bail out, take the prior one. Here's one way of many:
loopCounter = 2;
A(1) = 0; % Initialize
x(1) = A*rect((t-Tp/2)/Tp);
q(1) = trapz(x.^2)*periodo;
while (q<1)
A(loopCounter) = A(loopCounter-1) + 0.1;
x(loopCounter) = A(loopCounter-1)*rect((t-Tp/2)/Tp);
q(loopCounter) = trapz(x(loopCounter-1).^2)*periodo;
if q(loopCounter) >= 1
break; % Don't increment loop counter.
end
loopCounter = loopCounter + 1;
end
finalA = A(loopCounter - 1);
finalx = x(loopCounter - 1);
finalq = q(loopCounter - 1);

Community Treasure Hunt

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

Start Hunting!