Execute only once

Hi
I wrote a program in Embedded Matlab Function in Simulink. I have to define some variables as 0(zero) at first but they will be 0 only for the beginning. Then these variables are calculated in the program. Is there a way to execute the definatiion commands only once? Thanks in advice...

Réponses (2)

Fangjun Jiang
Fangjun Jiang le 23 Août 2011

1 vote

I guess you want to declare your variable persistent. type doc persistent for example. To initialize, you can do
if ~exist('VarName','var')
VarName=0;
end

3 commentaires

Kaustubha Govind
Kaustubha Govind le 23 Août 2011
The more standard way would be:
persistent VarName;
if isempty(VarName)
VarName = 0;
end
Fangjun Jiang
Fangjun Jiang le 23 Août 2011
Thank you Kaustubha for pointing it out. Indeed it needs to use isempty(), not to use exist(..,'var') because once the 'persistent VarName' line executes, the variable VarName will exist.
Coolman
Coolman le 3 Mar 2021
Could you do this for a figure also so I can make sure someone does not make tons of pop ups by clicking the same button multiple times?

Connectez-vous pour commenter.

Clemens
Clemens le 19 Jan 2012

0 votes

@Kaustubha:
Thanks a lot for the solution I just came across. By adding these 3 extra lines of code my Embedded Function executes about 100 times faster in simulation ;)

Catégories

En savoir plus sur Simulink dans Centre d'aide et File Exchange

Question posée :

le 23 Août 2011

Commenté :

le 3 Mar 2021

Community Treasure Hunt

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

Start Hunting!

Translated by