Multiple class constructor Matlab

Each class has only one constructor, and each .m-file can only contain one class definition.

If you want to have a class with slight differences depending on input, you can use properties that define switches that are recognized by the class methods. If you want to have very different classes depending on input, you can create a generateClass-function that will call either one or the other class defined in different files. Of course, if these different classes have lots of common methods and properties, you can create both as subclasses to a common superclass.


The answer of Pursuit works, but a user not familiar to the function can't see how many arguments are needed or what they are for. I would recommend this:

methods (Access = public)
    function self = Bicycle(startCadence, startSpeed, startGear)
        if nargin>2
            self.gear = startGear;
        else
            self.gear = 1;
        end
        self.cadence = startCadence;
        self.speed = startSpeed;        
    end
end

If you now type "Bicycle(" and wait you can see at least the three arguments. The second possibility is not shown though. It seems possible (e.g. for plot) but I don't know how to do this.


Each class has one constructor. However ... the constructor can accept any number and type of arguments, including those based on varargin.

So, to provide the option of a default third argument in Java you could write something like this (examples based on java documentation):

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}
public Bicycle(int startCadence, int startSpeed) {
    gear = 1;
    cadence = startCadence;
    speed = startSpeed;
}

In Matlab you could write

classdef Bicycle < handle
    properties (Access=public)
        gear
        cadence
        speed
    end
    methods (Access = public)
        function self = Bicycle(varargin)
            if nargin>2
                self.gear = varargin{3};
            else
                self.gear = 1;
            end
            self.cadence = varargin{1};
            self.speed = varargin{2};
        end
    end
end

Tags:

Oop

Matlab