Search code examples
matlabfor-loopwhile-loopsimulink

update a parameter in function block each timestep in simulink


I have the temperature (T) which should increase or decrease with a (delta_T) and it has an initial value of (T_0) and a (T_max = 100) So, I defined (delta_T = 10 or an equation) and (T_0 = 20) and it should be a loop (T = T + delta_T) which updates the value of T each time step. I will put this function in a block in Simulink. I am expecting the results T will be equal 30 then 40, 50, etc until it reaches 100 and stop. I tried for and while loop but failed I hope my question is clear and many thanks in advance.

I have tried the following but failed to update T

function [delta_T,T] = fcn(u) 
m=100; 
T = 20; 
delta_T = u/m;
T_max = 100; 
while T <= T_max 
T = T + delta_T;
end

Solution

  • If you include your code in a MATLAB function block, it will execute the entire "while" loop each time step.

    Change your function to

    function [delta_T,T_out] = fcn(u, T_in) 
    m=100; 
    % T = 20; % Note that this line is commented out
    delta_T = u/m;
    T_max = 100; 
    if T_in < T_max
        T_out = min(T_in + delta_T, T_max); 
    else
        T_out = T_in;
    end
    

    See screenshots of the model and results below:

    Example model

    Example results