MATLAB: Object properties that automatically update but aren’t Depenent

classesdependentgetmethodsobject-orientedoopset

I'm new to using object oriented programming, so I'm honestly just experimenting here, and maybe there's a better way to do this. For context I'm trying to create an object for an ideal gas.
classdef idealGas
properties
P
V
n
R = 8.314; %J/mol/K
T
end
end
Ideal gasses are defined by P*V = n*R*T, so I would like to be able to set any 3 (R is constant) and have the fourth calculated automatically. If only one of them were dependent, I could do
classdef idealGas
properties
P
V
n
R = 8.314;
end
properties (Dependent)
T
end
methods
function T = get.T(obj)
T = obj.P*obj.V/obj.n/obj.R;
end
end
end
gas1 = idealGas;
gas1.P = 100;
gas1.V = 2;
gas1.n = 5;
T = gas1.T;
I have two problems with this. First is that it only lets T be dependent; I would like to be able to specify any three and have it calculate the fourth. Second is that is would have to recalculate T every time I call it. This might not be a problem for this example since its a very simple operation, but for different objects it might not be. I would like it to be able to store T without recalculating every time I call it.
I tried having assigning other properties in a set method for P like follows, but it didn't like me accessing other properties in the set method for P.
function obj = set.P(obj,pressure)
if ~isempty(obj.P)
error('Pressure is already set, please change pressure via specific process')
end
obj.P = pressure;
obj.V = obj.n*obj.Rbar*obj.T/pressure;
obj.n = pressure*obj.V/obj.Rbar/obj.T;
obj.T = pressure*obj.V/obj.n/obj.Rbar;
end
Also even if that worked, I'd still have to do it for every property, which feels clunky.
Any ideas would be appreciated

Best Answer

function obj = set.P(obj,pressure)
if ~isempty(obj.P)
error('Pressure is already set, please change pressure via specific process')
end
obj.P = pressure;
obj.V = obj.n*obj.Rbar*obj.T/pressure;
obj.n = pressure*obj.V/obj.Rbar/obj.T;
obj.T = pressure*obj.V/obj.n/obj.Rbar;
end
So obj.P will have the new pressure value. obj.V will be calculated using the old n, Rbar, and T and the new P. Then obj.n will be calculated using the new pressure and V and the old Rbar and T. Do you then need to go back and recalculate obj.V using the new pressure and n and the old Rbar and T?
Giving a new value for any of the parameters will have a ripple effect on the others. I probably wouldn't try to use property set methods but I might use property get methods. If you're concerned about recomputing one of the parameters using a lengthy calculation consider using a memoize object.