MATLAB Answers

How to extend the colon operator for my own class

19 views (last 30 days)
Ernst Reissner
Ernst Reissner on 28 Feb 2021
Commented: Steven Lord on 1 Mar 2021
I am about to write an arithmetics for matlab.
Now I try to include the colon operator, i.e. to define the function colon for my class of numbers.
What do I have to do to implement the colon function? I know that the return type is a so called range
and for me as a java programmer it looks very much like an iterator,
i.e. an object allowing the functions hasnext(.) and next(.).
Please give me a hint on how to do it.

Answers (1)

Steven Lord
Steven Lord on 28 Feb 2021
The colon function in MATLAB for numeric inputs does not return an iterator, it returns a vector. See the documentation page for a description of what it returns and how it behaves for numeric inputs.
If you want your class's colon operator to behave the same way, it should return a vector of values from your class not an iterator object with methods hasnext and next. Doing so will satisfy the expectations of MATLAB functions that call colon on your class as to how it behaves.
  2 Comments
Steven Lord
Steven Lord on 1 Mar 2021
I was confused that it allows arrays so tall that they dont fit in memory.
I don't believe the tall array class has an overload of colon, actually. Many classes do including some of the classes in Parallel Computing Toolbox used to store data that can be operated on in parallel (including on a cluster, which could include data too large to fit in one machine's memory.) But not all do. For example, figure objects don't.
try
f1 = figure;
f2 = figure;
y = f1:f2;
catch ME
fprintf("The colon operator threw error:\n%s\n", ME.message)
end
The colon operator threw error: Undefined function 'colon' for input arguments of type 'matlab.ui.Figure'.
So I think, the colon operator returns a type of vector which is special in its implementation
That depends on your definition of "special". Most of time you'd expect the colon operator to return data of the type of one or more of its inputs. For example:
x = 1:2:10 % All three inputs double means the output is double
x = 1×5
1 3 5 7 9
t = datetime('today');
% the first and third inputs are datetime scalars (datetime + duration -> datetime)
% the second input is a duration scalar
% the output is a datetime array
dt = t:days(3):t+days(15)
dt = 1×6 datetime array
01-Mar-2021 04-Mar-2021 07-Mar-2021 10-Mar-2021 13-Mar-2021 16-Mar-2021
and contains its elements in a sense implicitly,
No. The vector explicitly contains its elements. x in the example above stores the numbers 1, 3, 5, 7, and 9. dt is a datetime array containing six values.
i.e. without assigning memory for each element, right?
No.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!