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.
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulink Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!