Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple class constructor Matlab

Tags:

Is it possible define more than one class constructor in Matlab? If yes, how?

like image 691
bsmca Avatar asked Apr 20 '12 22:04

bsmca


People also ask

Can a MATLAB class have multiple constructors?

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.

Can a class have multiple constructors?

A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.

What is a class constructor in MATLAB?

Purpose of Class Constructor Methods A constructor method is a special function that creates an instance of the class. Typically, constructor methods accept input arguments to assign the data stored in properties and return an initialized object. For a basic example, see Creating a Simple Class.

How do you call a superclass constructor in MATLAB?

To call the constructor for each superclass within the subclass constructor, use the following syntax: obj@SuperClass1(args,...);


1 Answers

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 
like image 128
Pursuit Avatar answered Oct 29 '22 07:10

Pursuit