MATLAB: Passing an object from a method function to another function

class function methods objects

I'm having trouble passing an object from a method function to another function.
I want to pass the obj.federaltax and obj.provincialTax to my calc_totalTax func to calcluate the totalTax but all i'm getting is an empty value for totalTax.
classdef calcTax
properties
income = input('enter annual income: ');
federalTax;
provincialTax;
totalTax;
end
function obj = calc_federalTax(obj)
if obj.income <= 46605
obj.federalTax = obj.income*15/100;
else
obj.federalTax = obj.income*15/100;
end
end
function obj = calc_provincialTax(obj)
if obj.income <= 42960
obj.provincialTax = obj.income*5.05/100;
else
obj.provincialTax = obj.income*9.15/100;
end
end
function obj = calc_totalTax(obj)
obj.totalTax = obj.provincialTax + obj.federalTax
disp(totalTax)
end
end
end

Best Answer

Nowhere in the code did you call your federal and provincial tax calculation methods. There are at least two possible solutions:
  • Call those calculation methods in your total tax calculation method.
function obj = calc_totalTax(obj)
obj = calc_provincialTax(obj);
obj = calc_federalTax(obj);
obj.totalTax = obj.provincialTax + obj.federalTax
disp(totalTax)
end
  • Make the three tax-related properties Dependent properties whose values are computed when you ask for them using the value of the non-Dependent income property. See this documentation page for a short example. In the example the Balance property is not stored in the object; it's computed using the values of the DollarAmount and Current properties that are stored in the object.