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

16 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 29 de Sept. de 2020
Editada: Ameer Hamza el 29 de Sept. de 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

Más respuestas (0)

Categorías

Más información sobre Simulink Functions en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by