MATLAB Object-Oriented Programming

(Joyce) #1

Class Support for Array-Creation Functions


In this section...
“Extend Array-Creation Functions for Your Class” on page 9-38
“Which Syntax to Use” on page 9-39
“Implement Support for Array-Creation Functions” on page 9-40

Extend Array-Creation Functions for Your Class


There are several MATLAB functions that create arrays of a specific size and type, such as
ones and zeros. User-defined classes can add support for array-creation functions
without requiring the use of overloaded method syntax.

Class support for any of the array-creation functions enables you to develop code that you
can share with built-in and user-defined data types. For example, the class of the variable
x in the following code can be a built-in type during initial development, and then be
replaced by a user-defined class that transparently overloads zeros:

cls = class(x);
zArray = zeros(m,n,cls);

Array-creation functions create arrays of a specific type in two ways:


  • Class name syntax — Specify class name that determines the type of array elements.

  • Prototype object syntax — Provide a prototype object that the function uses to
    determine the type and other characteristics of the array elements.


For example:

zArray = zeros(2,3,'uint8');

p = uint8([1 3 5 ; 2 4 6]);
zArray = zeros(2,3,'like',p);

After adding support for these functions to a class named MyClass, you can use similar
syntax with that class:

zArray = zeros(2,3,'MyClass');

Or pass an object of your class:

9 Methods — Defining Class Operations

Free download pdf