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

16 次查看(过去 30 天)
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.

采纳的回答

Ameer Hamza
Ameer Hamza 2020-9-29
编辑:Ameer Hamza 2020-9-29
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Simulink Functions 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by