MATLAB: Build a relay on code

controllerrelay

Good afternoon
I want to build a thermostat code in an existing building. I want to start the heater when the inside temperature (Tinv) is lower than a set point temperature (Ts) and turning it off when Tin reaches a maximum (Tmax). This problem is being conducted over a certain time period, so variables are Tin(j), Ts(j), Tmax(j).
The on/off variable is just a 1 or a 0 (v(j)). I wanted to build some kind of relay into it but it is not working for me so far, so I wanted to ask you people.
My code is as follows:
if Tinv(j)<=Ts(j)
v(j)=1;
if v(j-1)==1
v(j)=1;
else
if v(j-1)==0
v(j)=0;
end
end
end
Temperature just keep going down once it reaches the set point temp.
Thank you in advance,

Best Answer

You should sketch the two behaviors (don't use i or j as a variable name, and use comments to describe what your code is doing):
if Tin(t)<Ts
%temperature below setpoint, turn heating on
v(t)=1;
elseif v(t-1)==1 && Tin(t)>Tmax
%heating was on and max temp reached, turn off
v(t)=0;
else
%otherwise keep the same setting as last time interval
v(t)=v(t-1);
end