Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Simple MATLAB Class

Tags:

matlab

I am a Microsoft developer but trying to assist someone with some MATLAB code and design. I'm struggling to understand the syntax and usage of a class definition.

Code so far:

classdef Person

   properties
      Name 
   end

   methods

       function obj = Person(aName)
          obj.Name = aName;
       end

       function ret = IsGraeme(obj)
           if STRCMP( obj.Name , 'Graeme')
               ret= 1;
           else
               ret= 0;
           end
       end
   end
end

Now, I expect my usage to be similar to below:

graeme = Person('Graeme');
graeme.IsGraeme();

with the last line returning 1.

The first line of usage results in an error:

Too many inputs

The samples I have found on MATLAB seem to give you the classdef but not the usage.

I hope someone can help correct this simple example so that I can continue to build on it. (As mentioned, I am an experienced dev, just not in this language!).

UPDATE 1:

Using MATLAB 2013b.

Exact usage and resultant error below:

>> gt = Person('Graeme')
Error using Person
Too many input arguments.
like image 748
GinjaNinja Avatar asked Jan 18 '26 19:01

GinjaNinja


1 Answers

The OP's solution ended up being running the clear command in MATLAB. In all likelihood, what happened is an old class definition was already stored in memory and for some reason was not automatically updated. Anyhow - an easy fix!

Just in case others who stumble on this question what an explanation of the simplest basics of class constructors...

In MATLAB, you can an instance of a class without a constructor function, you follow the approach shown here, summed up below:

>> gt = Person();
>> gt.Name = 'Graeme';
>> gt.IsGraeme();

The OP wanted to create a constructor so that he could assign values to the class object's properties at initialization. Just for clarity's sake, a constructor is:

a method having the same name as the class.

The below (modified to fit OP's use-case) code is essentially copied from here. The only difference here is that we first check whether an input value has been provided before attempting to assign a (potentially undefined) value to a property of the instantiated class object:

function gt = Person(aName)
    if nargin > 0 % Check if more than 0 arguments are provided
        gt.Name = aName; % Assign input argument to property
    end
end

Now (as before), gt = Person('Graeme') will work as expected. This obviously assumes that the class is saved in a properly named M-file and that you've run clear to get rid of previous variable assignment mistakes.

like image 105
Vladislav Martin Avatar answered Jan 20 '26 15:01

Vladislav Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!