MATLAB 中 class 的使用

2016/3/18 posted in  MATLAB


基础

  • 定义类
classdef BasicClass
   properties
    Value
    end 
    methods
        function r = roundOff(obj)
           r = round([obj.Value],2);
       end
       function r = multiplyBy(obj,n)
            r = [obj.Value] * n;
        end 
    end
end
  • 创建实例
a = BasicClass
  • 访问属性

    • 赋值 a.Value = pi/3;

    • 获取 a.Value

例子:
第一次MATLAB编程走了很多坑,很多地方都不习惯

classdef Term
    %UNTITLED4 Summary of this class goes here
    %   Detailed explanation goes here
    
    properties
        termGPA %学期绩点
        %termName %第一学期/第二学期
        lessons = []
        termNo
    end
    
    methods
        function self = Term(name,gpa,lessons)
            %String,Double,[Lesson]?
            self.lessons = lessons;
            
            self.termGPA = gpa;
            if isequal(name,'第一学期')
                self.termNo = 1;
            else
                self.termNo = 2;
            end
        end
        
        function  self = appendLessons(self,newLessons)
            self.lessons = [self.lessons,newLessons];
           
        end
     
    end
    
end


一开始appendLessons想当然地写成了

function   appendLessons(self,newLessons)
            self.lessons = [self.lessons,newLessons];
           
end

后来发现实际对象的属性并没有变,改成self = appendLessons(self,newLessons)就OK了