Can I assign types to class properties in MATLAB?

后端 未结 3 1625
死守一世寂寞
死守一世寂寞 2020-12-14 20:48

I\'m new to using MATLAB as an object-oriented environment and I\'m writing my first class to describe a network packet. A simple example would be the following



        
3条回答
  •  鱼传尺愫
    2020-12-14 21:13

    Since it is not possible to explicitly specify types for variables in Matlab, you cannot do this when declaring properties.

    However, you can define a set method which checks the class and either throws an error or converts the input to whatever you want.

    For example

    classdef myClass
       properties
          myProperty = uint16(23); %# specify default value using correct type
       end
       methods
          function obj = set.myProperty(obj,val)
             if ~isa(val,'uint16')
                error('only uint16 values allowed')
             end
             %# assign the value
             obj.myProperty = val;
          end
       end
    end
    

提交回复
热议问题