Search code examples
matlabsimulationstatements

MATLAB - how to create condition with specific requirements


I'm simulating water heating and I need to create certain condition and I dont know how to create it properly.

Required temperature of water is 55 °C. Minimal temperature is 50 °C. Maximum temperature is 70 °C.

I have 2 types of heating - electrical heating which heats water to required temperature 55 °C and photovoltaic heating which can heat water to maximum temperature.

I need to create condition which turn on electrical heating only if temperature drops below 50 °C and stops after reaching 55 °C. If the temperature is between 50 and 55 without previously dropping under 50 °C only photovoltaic heating is possible and electrical heating is off.

Temperature is checked every minute for whole year. Conditions will be placed in for cycle.

Right now, I have it without condition for required temperature (55 °C) like this:

for i = 1:525600
    if (temeprature(i) < 70)
           heating = 1; %heating from photovoltaic
       else
           heating = 0; % heating off
       end
         if (temperature(i) < 50)
          heating = 2; % electric heating when there is not enough power from PV                   
         end
   if heating==0
     calculations
     calling functions
     etc.
     ...
    end
   if heating==1
     calculations
     calling functions
     etc.
     ...
    end 
   if heating==2
     calculations
     calling functions
     etc.
     ...
    end 
 computing temperature with results from conditions
 end

Thanks for any advice.


Solution

  • I would make a function with persistent variable for electric heating:

    function [el, pv] = whatHeating(T)
    persistent elHeat
    if (isempty(elHeat))
        elHeat = false; % Initialize to false. The only thing where it matters is if you start at 50<T<55.
    end
    
    if (T < 50)
        elHeat = true;
    elseif (T > 55)
        elHeat = false;
    end
    el = elHeat; % You can't return persistent variable directly.
    
    if (T > 70)
        pv = false;
    else
        pv = true;
    end
    

    Then you simply call this function in your main one.