0
votes

I have a Matlab function block in Simulink that receives 2 inputs and processes it to generate an output. During the course of the simulation, at some time points, one of the inputs is zero. I'd like to use the most recent non-zero input to the function whenever that particular input value is zero. How can I achieve this? I tried creating a persisent variable that updates to most recent non-zero input value but that doesn't seem to work.

EDIT 1 (to include code):

function y = fcn(u)

persistent ref_val

if isEmpty(ref_val)
   ref_val=10.0
end

if(u(1)<=25)
   y=20.0
else
   if(u(2)>0)
      y=u(2)
      ref_val=u(2) 
   else
      y=ref_val
   end 
end

EDIT 2: For now, I fixed the issue by writing a C code that uses a static variable to retain the most recent non-zero input value. But I still welcome suggestions/solutions to realize this directly in a Matlab function.

1
A persistent variable is the way to do this. Show us your code.Phil Goddard
Phil, sorry I should have included the code. Please see edit.arun
The code appears correct? With the exception that I believe "isEmpty" should instead be "isempty" as MATLAB is case sensitive for built-in functions.DMR
As @DMR says, the code looks OK, so it's probably a data issue. Is u(2) a double precision number? And what is it's range of values? Where I'm going with those questions is if u(2) is double precision, perhaps you think you're inputting (exactly) 0.0 when in fact you might be inputting 0.00000001 (or something similarly small), which is not actually 0.Phil Goddard
Arun, can you please attach the model wherein you have used the function block? The code looks absolutely fine so there must be problem in the environment (simulink input/output).Akanksha

1 Answers

-1
votes

Can't you use something like this in your simulation?

//Find the index of the last non-zero value in the input

[~,last_non_zero] = max(find(input(1:i) > 0))

//Call the function using this input

output = fnc(input(last_non_zero))