classdef TensileData % 定义类的名称
properties %% 定义类的属性,相当于C++中的成员函数
Material = 'carbon steel';
SampleNumber = 0;
Stress
Strain
end
properties (Dependent) %% 定义依赖型属性,该属性只能通过类内的方法进行赋值,参考modulus = get.Modulus(obj)
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 % TensileData
end
methods %% 定义类的方法
function obj = set.Material(obj,material)
if ~(strcmpi(material,'aluminum') ||...
strcmpi(material,'stainless steel') ||...
strcmpi(material,'carbon steel'))
error('Material must be aluminum, stainless steel, or carbon steel')
end
obj.Material = material;
end % Material set function
function modulus = get.Modulus(obj)
ind = find(obj.Strain > 0); % Find nonzero strain
modulus = mean(obj.Stress(ind)./obj.Strain(ind));
end % Modulus get function
function obj = set.Modulus(obj,~) % 不能显式定义依赖型属性变量
fprintf('%s%d\n','Modulus is: ',obj.Modulus)
error('You cannot set Modulus explicitly');
end
function disp(td)
fprintf(1,'Material: %s\nSample Number: %g\nModulus: %1.5g\n',...
td.Material,td.SampleNumber,td.Modulus);
end % disp
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 % plot
end
methods (Access = 'private') % 只能通过类的成员进行访问 私有成员方法
function m = CalcModulus(td)
% Over-simplified calculation of Elastic Modulus
ind = find(td.Strain > 0); % Find nonzero strain
m = mean(td.Stress(ind)./td.Strain(ind));
end % CalcModulus
end
end % classdef
matlab类封装
最新推荐文章于 2024-09-19 10:33:20 发布