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 endend
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 endendgas1 = 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