Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign types to class properties in MATLAB?

Tags:

oop

class

matlab

I'm new to using MATLAB as an object-oriented environment and I'm writing my first class to describe a network packet. A simple example would be the following

classdef Packet

    properties
        HeaderLength
        PayloadLength
        PacketType
    end

end

I would like to explicitly specify that HeaderLength and PayloadLength are both uint16's and PacketType is a string. Is there a way to do this?

like image 856
Phonon Avatar asked Aug 25 '11 14:08

Phonon


People also ask

What are class properties in MATLAB?

Classes define the same properties for all object, but each object can have unique data values. Property attributes control what functions or methods can access the property. You can define functions that execute whenever you set or query property values. Properties can trigger events when code accesses their values.

How do I add a property to an object in MATLAB?

P = addprop( A , PropertyName ) adds a property named PropName to each object in array A . The output argument P is an array of meta. DynamicProperty objects that is the same size as A . Dynamic properties exist only on the specific instance for which they are defined.

Can you write classes in MATLAB?

Creating classes can simplify programming tasks that involve specialized data structures or large numbers of functions that interact with special kinds of data. MATLAB classes support function and operator overloading, controlled access to properties and methods, reference and value semantics, and events and listeners.


1 Answers

There exist an undocumented syntax to enforce property types:

classdef Packet
    properties
        HeaderLength@uint16
        PayloadLength@uint16 = uint16(0);
        PacketType@char
    end
end

If you try to set a property with the wrong type, you get an error:

>> p = Packet;
>> p.PacketType = 'tcp';
>> p.HeaderLength = 100;
While setting the 'HeaderLength' property of Packet:
Value must be 'uint16'.

As far as I can tell, this syntax support all primitive types like: char, int32, double, struct, cell, ..., in addition to any user-defined ones (just use any class name).

Note that setting the type as above seems to override any "set method" if any.

I just came across this syntax being used in an internal class in R2013a (toolboxdir('matlab')\graphics\+graphics\+internal\+figfile\@FigFile\FigFile.m), but it also worked in R2012a, probably older versions as well...

like image 125
Amro Avatar answered Oct 16 '22 17:10

Amro