Catalogue
Using classes to represent structured data
Create an instance and assign it to data
Restrict attributes to specific values
Simplify interfaces with constructors
Method of drawing stress versus strain diagram
Using classes to represent structured data
Object as data structure
The following example defines a class for storing data with a specific structure. Using a consistent structure to store data makes it easier to create functions to manipulate data. MATLAB ® struct} can contain field names that describe specific data elements, which is a useful way to organize data. However, classes can define data stores (properties) and operations (Methods) performed on that data. This example illustrates these advantages.
Example background
For this example, the data represents tensile stress / strain measurements. These data are used to calculate the elastic modulus of various materials. In short, stress is the force applied to a material, and strain is the resulting deformation. Its ratio determines the properties of the material. Although this method is a greatly simplified process, it is enough to meet the purpose of this example.
Data structure
The following table describes the structure of the data.
data | explain |
---|---|
Material | char vector that identifies the type of material being tested |
SampleNumber | Number of test sample |
Stress | A numerical vector representing the stress applied to the specimen during the test. |
Strain | A numerical vector representing the strain at the corresponding value of the applied stress. |
Modulus | Defines the value of the elastic modulus of the material under test, which is calculated from the stress and strain data |
TensileData class
The following example starts with a simple implementation of a class and uses this implementation as a basis to illustrate how features enhance the usefulness of a class. The first version of this class provides only data storage. This class defines an attribute for each required data element.
classdef TensileData properties Material SampleNumber Stress Strain Modulus end end
Create an instance and assign it to data
The following statement will create a TensileData object and assign data to it:
td = TensileData; td.Material = 'Carbon Steel'; td.SampleNumber = 001; td.Stress = [2e4 4e4 6e4 8e4]; td.Strain = [.12 .20 .31 .40]; td.Modulus = mean(td.Stress./td.Strain);
Advantages of class over structure
Process the # TensileData # object (in the previous statement, # td) like any matlab structure. However, defining a specialized data structure as a class has the following advantages over using a general data structure (such as MATLAB # struct):
-
When users accidentally misspell the field name, they will receive an error message. For example, type the following:
td.Modulis = ...
A field is added directly to the structure. However, if td is an instance of the TensileData class, an error is returned.
-
Classes are easy to reuse. Once a class is defined, you can easily extend it with subclasses that add new properties.
-
Classes are easy to identify. Classes have names, so you can use whos and class functions and workspace browsers to identify objects. Using class names, you can easily reference records with meaningful names.
-
When assigning values, the class can verify the values of various fields, including classes or values.
-
Class can restrict access to a field, for example, allowing a specific field to be read but not changed.
Restrict attributes to specific values
You can limit attributes to specific values by defining attribute set access methods. MATLAB will call the set access method every time it sets the attribute value.
Material property set function
The Material # property set method limits the assignment of the property to one of the following strings: aluminum, stainless steel # or # carbon steel. Add this function definition to the method code block.
classdef TensileData properties Material SampleNumber Stress Strain Modulus 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 trying to set the material property, MATLAB calls set before setting the property value Material method. If the value matches the acceptable value, the function sets the property to that value. The code in the set method can directly access the property to avoid calling the property set method recursively.
For example:
td = TensileData; td.Material = 'brass'; Error using TensileData/set.Material Invalid Material
Simplify interfaces with constructors
Simplify the interface with TensileData class by adding a constructor:
-
Enables you to pass data as parameters to the constructor
-
Assign values to attributes
The constructor is a method with the same name as the class.
methods function td = TensileData(material,samplenum,stress,strain) if nargin > 0 td.Material = material; td.SampleNumber = samplenum; td.Stress = stress; td.Strain = strain; end end end
Create a TensileData object that is fully populated with data using the following statement:
td = TensileData('carbon steel',1,... [2e4 4e4 6e4 8e4],... [.12 .20 .31 .40]);
On demand calculation data
If the value of a property depends on the value of other properties, use the Dependent attribute to define the property. MATLAB does not store values of Dependent attributes. When accessing a Dependent property, the Dependent property get method is used to determine the property value. It can be accessed when displaying object properties or as the result of an explicit query.
Calculation modulus
TensileData object does not store the value of the module property. The constructor does not have an input parameter for the value of the Modulus property. Value of module:
-
Calculated from the values of the Stress and string attributes
-
When the value of the Stress or string attribute changes, it must also change
Therefore, it is best to calculate the value of the module attribute only when needed. Use the property get access method to calculate the value of Modulus.
Module property get method
The "module" attribute depends on "Stress" and "Strain", so its "Dependent" attribute is "true". Put the 'module' attribute in a separate 'properties' code block and set the' Dependent 'attribute.
get. The module} method calculates and returns the value of the} module} property.
properties (Dependent) Modulus end
Only the default attribute is used to define the property get method in the methods code block.
methods function modulus = get.Modulus(obj) ind = find(obj.Strain > 0); modulus = mean(obj.Stress(ind)./obj.Strain(ind)); end end
This method calculates the average ratio of stress and strain data after eliminating zero in denominator data. When querying properties, MATLAB will call
get.Modulus
Methods. For example:
td = TensileData('carbon steel',1,... [2e4 4e4 6e4 8e4],... [.12 .20 .31 .40]); td.Modulus ans = 1.9005e+005
Modulus property set method
To set the value of the Dependent property, the class must implement the property set method. You do not need to allow the module property to be set explicitly. However, you can use the set method to provide custom error messages. The module set method refers to the current property value and returns an error:
methods function obj = set.Modulus(obj,~) fprintf('%s%d\n','Modulus is: ',obj.Modulus) error('You cannot set the Modulus property'); end end
Display TensileData object
TensileData class overloads the {disp} method. This method controls the display of objects in the command line window. The disp ¢ method displays the values of the ¢ Material, SampleNumber, and module ¢ properties. It does not display the , Stress , and , Strain , attribute data. These properties contain raw data that is not easy to view in the command line window.
The disp # method uses fprintf # to display formatted text in the command line window:
methods function disp(td) fprintf(1,... 'Material: %s\nSample Number: %g\nModulus: %1.5g\n',... td.Material,td.SampleNumber,td.Modulus); end end
Method of drawing stress versus strain diagram
Viewing the stress / strain data graph helps to determine the behavior of the material within the range of applied tension. The TensileData} class overloads the MATLAB plot function.
The plot # method creates a linear graph of stress strain data and adds a title and axis label to generate a standardized graph of tension data record:
methods function plot(td,varargin) plot(td.Strain,td.Stress,varargin{:}) title(['Stress/Strain plot for Sample',... num2str(td.SampleNumber)]) ylabel('Stress (psi)') xlabel('Strain %') end end
The first parameter of this method is the TensileData object that contains the data. This method passes the variable list (varargin) of the parameter directly to the built-in {plot} function. The TensileData # plot # method allows you to pass a line setter parameter or attribute name value pair group.
For example:
td = TensileData('carbon steel',1,... [2e4 4e4 6e4 8e4],[.12 .20 .31 .40]); plot(td,'-+b','LineWidth',2)
TensileData} class summary
Sample code | discuss |
---|---|
classdef TensileData | Value classes support independent copies of objects. |
properties Material SampleNumber Stress Strain end | Reference data structure |
properties (Dependent) Modulus end | Module is calculated when querying. |
methods | For general information about methods, refer to original methods. |
function td = TensileData(material,samplenum,... stress,strain) if nargin > 0 td.Material = material; td.SampleNumber = samplenum; td.Stress = stress; td.Strain = strain; end end | Refer to simplifying interfaces with constructors. Reference class constructor method. |
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 | Limit the possible values of the Material attribute. function m = get.Modulus(obj) ind = find(obj.Strain > 0); m = mean(obj.Stress(ind)./obj.Strain(ind)); end |
The module attribute is evaluated when querying. | |
function obj = set.Modulus(obj,~) fprintf('%s%d\n','Modulus is: ',obj.Modulus) error('You cannot set Modulus property'); end | Add a set method for the # Dependent # module # property. |
function disp(td) fprintf(1,'Material: %s\nSample Number: %g\nModulus: %1.5g\n',... td.Material,td.SampleNumber,td.Modulus) end | Overload the {disp} method to display specific properties. |
function plot(td,varargin) plot(td.Strain,td.Stress,varargin{:}) title(['Stress/Strain plot for Sample',... num2str(td.SampleNumber)]) ylabel('Stress (psi)') xlabel('Strain %') end | Reload the plot function to accept the # TensileData # object and the graph of stress versus strain. |
end end |
Expand class code:
classdef TensileData properties Material SampleNumber Stress Strain end properties (Dependent) Modulus end methods function td = TensileData(material,samplenum,stress,strain) if nargin > 0 td.Material = material; td.SampleNumber = samplenum; td.Stress = stress; td.Strain = strain; end end 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 function m = get.Modulus(obj) ind = find(obj.Strain > 0); m = mean(obj.Stress(ind)./obj.Strain(ind)); end function obj = set.Modulus(obj,~) fprintf('%s%d\n','Modulus is: ',obj.Modulus) error('You cannot set Modulus property'); end function disp(td) sprintf('Material: %s\nSample Number: %g\nModulus: %1.5g\n',... td.Material,td.SampleNumber,td.Modulus) end function plot(td,varargin) plot(td.Strain,td.Stress,varargin{:}) title(['Stress/Strain plot for Sample ',... num2str(td.SampleNumber)]) xlabel('Strain %') ylabel('Stress (psi)') end end end