Search code examples
matlabdata-structurestypes

Defining a structured type in Matlab


I'm pretty sure there's a feature for that in the Matlab programming/script language, but I cannot find it. I guess I'm googling with the wrong words.

What I want to do is define a category of data items that will all share the same internal structure.

Like this:

I declare PERSON to be a type of structure consisting of:
   FIRST NAME  : text;
   LAST NAME : text;
   PHONE NUMBER : integer;;

Now I declare the following variables:

PERSON MIKE

PERSON JANE

How can I do that?


Solution

  • The type you are searching for is 'Class'

    classdef Person
    properties
        FirstName string % *
        LastName string 
        PhoneNumber double {mustBePositive,mustBeInRange(PhoneNumber,0000000000,99999999999)} % **
    end
    end
    

    Some notes:

    • the class must be in its own separate .m file which has to have the same name as the class itself
    • you can set validation in the property section itself. It can be of type (*) or of more complex nature (**). You can read more here Class Validation Docs
    • Classes may or may not have methods, but still give them a look. Some methods like constructors, ... can be useful in any case.
    • Be careful to not override already existent classes (the name is important)

    To call the class just do:

     mike = person; %creates mike object
     mike.LastName='VeryImportantSurname' %assigns to its property
    

    if you were to use constructors the code (incomplete for case handling, just an example) would be instead:

       classdef person
        properties
            FirstName string
            LastName string
            PhoneNumber double ...
                {mustBePositive,mustBeInRange(PhoneNumber,0000000000,99999999999)}
        end
    
        methods
            function obj=person(Fn,Ln,Pn)
                if nargin == 3
                    obj.FirstName=Fn;
                    obj.LastName=Ln;
                    obj.PhoneNumber=Pn;
                end
            end
        end
    end 
    

    This would allow to call and assign directly:

    mike=person('Mike','VeryImportantSurname',87345929) %creates mike object and assigns properties