Simulink: abnormal behavior using 'persistent' variable (bug?)
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Hey there, out of a more complex model I minimized the problem to the following code, running in a Matlab Function block in Simulink:
Solver: auto Type: fixed step, solverstep = 0.1
What the function is supposed to do:
- get the running time
- calculate new values at time == 0.1, 1.1, 2.1,... (=> t_unblock_takt = 1)
- hold the outport values: 0.1 < t < 1.1; 1.1 < t < 2.1; ... and so on
function [time_0, t_unblock_0, value_to_be_calculated_0] = CTRL(time)
persistent t_unblock value_to_be_calculated;
if isempty (t_unblock, value_to_be_calculated)
t_unblock = 0.1;
value_to_be_calculated = 0;
end
t_block_takt = 1;
if time == t_unblock
t_unblock = t_unblock + t_block_takt;
time_sim = time;
value_to_be_calculated = value_to_be_calculated + 1;
else
time_sim = time;
end
%%OUT
time_0 = time_sim;
t_unblock_0 = t_unblock;
value_to_be_calculated_0 = value_to_be_calculated;
end
As you can see, t_unblock is being updated correctly until 4.1. After this time, it is not being updated any more. So, value_to_be_calculated is not being updated as well. It seems, the
if time == t_unblock
works not correctly.
What am I doing wrong? Is there an issue with using persistent? But if yes, why does it always stop at the same time to work?
Thank you,
AL
3 Commenti
Vidya Viswanathan
il 13 Lug 2016
Modificato: Vidya Viswanathan
il 13 Lug 2016
I believe this behavior is due to the precision loss that is inherent in representing floating-point numbers in any system. When you actually step through the MATLAB function block at time step t=4.1, you can observe that the two values "time" and "t_unblock" are slightly different. To observe that, change the format of data representation to long (by typing "format long" in MATLAB) and hovering over the two variables. This is the reason why "time==t_unblock" condition does not evaluate to true when t = 4.1.
I hope this helps.
Regards,
Vidya Viswanathan
Risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!