why does an "if" statement inside a MATlab function block in simulink not trigger?

I am trying to create a "switch" of sorts within my simulink model. I have a system that takes in 3 numbers, and if all 3 numbers are below a value, it will increase my counter (k) by 1. Once my counter reaches a value (lets say 5 for example), the block will change the value it is outputting.
The blocks in simulink are shown in the picture.
The code inside the MATLAB function is as follows:
function [R,k] = fcn(eR,eV,eA,k,rHold, rDock)
if k > 5
R = rDock;
else
R = rHold;
end
if (k <= 5)
if((abs(eR) < 0.2) && (abs(eV) < 0.1) && (abs(eA) < 0.2))
k = k + 1;
end
end
end

6 comentarios

I would recommend double-checking that k is a scalar.
assert(length(k) == 1)
and non-nan
assert(~isnan(k))
I tried inserting both commands at the beginning of the function, and neither of them produced an error. Maybe I input them incorrectly?
function [R,k] = fcn(eR,eV,eA,k,rHold, rDock)
assert(~isnan(k))
assert(length(k)==1)
...
Can you provide a minimal not-working example? Are eR, eV and eA all small enough? Which if statement does not trigger?
I ran your funtion with some dummy inputs and it looked fine.
eR=0.01;
eV=0.01;
eA=0.01;
rDock=1;
rHold=2;
k=0;
for i=1:10
[R,k]=fcn(eR,eV,eA,k,rHold,rDock)
end
function [R,k] = fcn(eR,eV,eA,k,rHold, rDock)
if k > 5
R = rDock;
else
R = rHold;
end
if (k <= 5)
if((abs(eR) < 0.2) && (abs(eV) < 0.1) && (abs(eA) < 0.2))
k = k + 1;
end
end
end
So unfortunately I think that this as simple as it gets without including the rest of the simulink. I tested around with which "if" statements didn't work, and what I found is that none of them work. I commented out the second set of "if" statements and left the k=k+1 so that at every iteration, k would increase, and the counter itself works. So it is confirmed an issue with the if statements.
As far as values not triggering the conditions, I have plots that are made from the simulink and after about 30 seconds of simulation, all 3 of those values become less than 0.009 so they should all trigger.
What happens if you add
assert( ((abs(eR) < 0.2) && (abs(eV) < 0.1) && (abs(eA) < 0.2)) )
at the top of the function?
Hello everyone, so I made a silly mistake and forgot about a block that I connected to the simulink. Turns out the controller I made works, it just wasn't feeding into the correct block elsewhere.
Thanks for all the help! I definitely learned some new commands to help me debug in the future!

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Simulink en Centro de ayuda y File Exchange.

Productos

Versión

R2018a

Preguntada:

el 2 de Ag. de 2018

Comentada:

el 3 de Ag. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by