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

1 回表示 (過去 30 日間)
AL
AL 2016 年 6 月 29 日
編集済み: Stephen23 2016 年 7 月 13 日
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 件のコメント
Vidya Viswanathan
Vidya Viswanathan 2016 年 7 月 13 日
編集済み: Vidya Viswanathan 2016 年 7 月 13 日
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 2016 年 7 月 13 日
編集済み: Stephen23 2016 年 7 月 13 日
@Vidya Viswanathan: You should put your comment as an answer: it might get accepted.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeSimulink についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by