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

1 view (last 30 days)
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 Comments
Vidya Viswanathan
Vidya Viswanathan on 13 Jul 2016
Edited: 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.
Regards,
Vidya Viswanathan
Stephen23
Stephen23 on 13 Jul 2016
Edited: Stephen23 on 13 Jul 2016
@Vidya Viswanathan: You should put your comment as an answer: it might get accepted.

Sign in to comment.

Answers (0)

Categories

Find more on Simulink in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!