Check if the condition happened in previous cycles

I'm trying to make a condition to analyze every 5 cycles, but I need the value of p_fix (threshold) not to exceed PE. As I did, it only analyzes when it reaches 5 cycles, but I needed to check if PE>p was respected until it reaches 5 cycles again and again.
if mod(n,5)==0 && PE(n-1,1)>p_fix
fprintf('Accuses IC\n')

 Accepted Answer

Matt J
Matt J on 29 Dec 2021
Edited: Matt J on 29 Dec 2021
Update a boolean flag to keep track of it.
flag=true; %initial state
for n=1:N
flag=flag & PE(n-1,1)>p_fix;
if mod(n,5)==0 && flag
fprintf('Accuses IC\n')
end

5 Comments

In my case I can't declare the initial state before the for since the values of PE and p_fix are calculated inside it. And the initial state of p_fix is [].
complete code
p_fix = [];
for n = 4:size(t,1)
X = [Ia(n-1,1) Ia(n-2,1) ; Ia(n-2,1) Ia(n-3,1)];
future = [Ia(n,1) ; Ia(n-1,1)];
C = X\future;
Ia_future(n,1) = C(1,1)*Ia(n,1)+C(2,1)*Ia(n-1,1);
PE(n,1)=Ia(n,1)+Ia_future(n,1);
p(n,1)=(1+0.2)*max(PE(n-1,1));
flag=(PE(0,1)>p_fix);
flag=flag & PE(n-1,1)>p_fix
if (isnan(PE(n-1, 1)) || PE(n-1, 1) == 0) || (isnan(p(n, 1)) || p(n, 1) == 0)
continue
end
if isempty(p_fix) && PE(n-1,1)>p(n,1)
p_fix = p(n,1);
if mod(n,5)==0 && flag
fprintf('Accuses IC\n')
else
fprintf('Does not accuse IC\n')
p_fix = [];
end
end
end
Unrecognized function or variable 't'.
Then he accuses the following error:
Operands to the || and && operators must be convertible to logical scalar values.
Error in linear_prediction (line 35)
if mod(n,5)==0 && flag
Matt J
Matt J on 29 Dec 2021
Edited: Matt J on 29 Dec 2021
I've edited your previous comment and Run the code in it. As you can see there, it doesn't produce the error you claim.
You use
flag=(PE(0,1)>p_fix);
in your code. But PE(0,1) does not exist and p_fix is not initialized to a real number. So flag is not initialized to logical.
OK, yes. Now it worked, thank you all

Sign in to comment.

More Answers (0)

Categories

Asked:

on 29 Dec 2021

Edited:

on 29 Dec 2021

Community Treasure Hunt

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

Start Hunting!