How to initialize a variable to zero in userdefined matlab function, which should be executed only once then the values should change dynamically

16 Ansichten (letzte 30 Tage)
function [ia_avr] = fcn(ia)
iasum = iasum+Ia;
if xxxx
ia_num=ia_num+1;
ia_avr=ia_avr_old;
elseif xxxx
ia_num=ia_num+1;
ia_avr=iasum/ia_num;
ia_avr_old=ia_avr;
else
ia_avr=ia_avr_old;
iasum=0;
ia_num=0;
end
end
In this I want to initialize iasum,ia_num,ia_avr_old to 0. After which the values should change.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 29 Sep. 2020
Bearbeitet: Ameer Hamza am 29 Sep. 2020
Such cases are handled using persistent variables.
function [ia_avr] = fcn(ia)
persistent iasum ia_num ia_avr_old
if isempty(iasum) % only runs once
iasum = 0;
ia_num = 0;
ia_avr_old = 0;
end
iasum = iasum+Ia;
if xxxx
ia_num=ia_num+1;
ia_avr=ia_avr_old;
elseif xxxx
ia_num=ia_num+1;
ia_avr=iasum/ia_num;
ia_avr_old=ia_avr;
else
ia_avr=ia_avr_old;
iasum=0;
ia_num=0;
end
end

Weitere Antworten (0)

Kategorien

Mehr zu Simulink Functions finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by