What does this MATLAB class to and why isn't i

2019-03-05 15:39发布

问题:

The very first one in this documentation: http://www.mathworks.com/help/matlab/matlab_oop/getting-familiar-with-classes.html

The class is:

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

When I run it this way

a = BasicClass
a.Value = pi/3;

It works fine and does what it should but this piece of code

a = BasicClass(pi/3);

Gives the following error:

"Error using round

Too many input arguments."

What does it mean? (I'm using R2014a) Is it stupid to use oop in Matlab? LOL

回答1:

Your error message doesn't look correct compared with the code, whichever your missing a class constructor (as is mentioned at the half way down the help link):

classdef BasicClass
  properties
    Value
  end
  methods

    % Class constructor -> which you can pass pi/3 into.
    function obj = BasicClass ( varargin )
      if nargin == 1
        obj.Value = varargin{1};
      end
    end

    % Your Methods
    function r = roundOff(obj)
      r = round([obj.Value],2);
    end
    function r = multiplyBy(obj,n)
      r = [obj.Value] * n;
    end
  end
end