MATLAB Object-Oriented Programming

(Joyce) #1
end
methods
function obj = set.Material(obj,material)
if (strcmpi(material,'aluminum') ||...
strcmpi(material,'stainless steel') ||...
strcmpi(material,'carbon steel'))
obj.Material = material;
else
error('Invalid Material')
end
end
end
end

When there is an attempt to set the Material property, MATLAB calls the
set.Material method before setting the property value.

If the value matches the acceptable values, the function set the property to that value.
The code within set method can access the property directly to avoid calling the property
set method recursively.

For example:

td = TensileData;
td.Material = 'brass';

Error using TensileData/set.Material
Invalid Material

Simplifying the Interface with a Constructor


Simplify the interface to the TensileData class by adding a constructor that:


  • Enables you to pass the data as arguments to the constructor

  • Assigns values to properties


The constructor is a method having the same name as the class.

methods
function td = TensileData(material,samplenum,stress,strain)
if nargin > 0
td.Material = material;
td.SampleNumber = samplenum;

3 MATLAB Classes Overview

Free download pdf