MATLAB Answers

Simulink: abnormal behavior using 'persistent' variable (bug?)

1 view (last 30 days)
AL on 29 Jun 2016
Edited: Stephen Cobeldick on 13 Jul 2016
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;
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;
time_sim = time;
time_0 = time_sim;
t_unblock_0 = t_unblock;
value_to_be_calculated_0 = value_to_be_calculated;
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 on 29 Jun 2016
I should add: if I set
t_unblock = 1
t_block = 1
everything works fine. I can't explain it to myself. If it would belong to data types (int, double...), why does the configuration 0.1 / 1 work until 4?
Vidya Viswanathan
Vidya Viswanathan on 13 Jul 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.
Vidya Viswanathan
Stephen Cobeldick
Stephen Cobeldick on 13 Jul 2016
@Vidya Viswanathan: You should put your comment as an answer: it might get accepted.

Sign in to comment.

Answers (0)

Translated by