Matlab Function Block in Simulink Model_ using persistent variables to hold previous values
1 view (last 30 days)
Show older comments
Hi there!
I have this MATLAB Function Block within a Simulink Model: the function takes a voltage measurment from the Simulink model as an input and it outputs the drive signal for a switch.
I would like to be able to fire the switch when some condition is TRUE, and then keep the switch ON until the measured voltage is higher by N voltages than its value when the switch is first fired.
I am using persistent variables to store the voltage measurment (at the moment the switch is fired) and the previous drive signal. I am not sure why my code does not function properly. I would appreciate your suggestions. Thanks
Here the piece of the code inside the MATLAB Function Block:
.
.
.
persistent prev_Volt;
persistent prev_G;
if isempty(prev_G)
prev_G = 0;
end
if isempty(prev_Volt)
prev_Volt = measured_Volt;
end
if (ARM==1)
G = 1; %fire the switch
if prev_G == 0
prev_Volt = measured_Volt; % update prev_volt only when G transitions from 0 to 1
elseif measured_Volt > (prev_Volt + N)
G = 0; prev_Volt = measured_Volt; %Reset the switch when it exceeds N voltage higher than when it was initially fired
end
else
G = 0;
end
% Store the current value of G for the next time step
prev_G = G;
.
.
.
0 Comments
Answers (1)
madhan ravi
on 2 Dec 2023
change prev_DcBusVolt to pre_Volt
2 Comments
madhan ravi
on 2 Dec 2023
Edited: madhan ravi
on 2 Dec 2023
Puh. You make too many typos (Change GR to G). MATLAB doesn’t care if it’s typo or not. If G is a gate signal, then I would suggest you to have it’s value as Boolean than double.You say when G transition from 0 to 1 but only check if previous G value is equal to 0 and forgot about the current G value.
if (prev_G == 0) && (G == 1) % change your code to this
I don’t have access to Simulink at the moment. But I would simply prefer implementing this logic in Simulink directly.
Note: when comparing for conditions make sure ARM and measured_Volt are (Boolean or int) or float. If it’s float you need to make floating point comparison with tolerances, otherwise the if - condition won’t be executed.
See Also
Categories
Find more on Model Verification 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!