Pointers and subscript pointers

Pointers implemented in Matlab
Updated 31 Jan 2011

View License

The hnum class is a handle to a value class (uint8, double, etc). It acts like a pointer, but isn't really a pointer. Operating on an hnum class does not require "x = x + 1". Using "x+1" will permanantly modify it's value. Copying an hnum object only creates a copy to it's handle, and doesn't copy it's data. In the example "y = x", if x changes, y also changes.

There are two subscripting modes for the hnum class. The default is 'normal'. In the normal mode, "a = x(1:3)" returns a value, not a handle. In the 'pointer' mode, "a = x(1:3)" returns a pointer to the first three
elements of x. This is a subscripthandle class. Modifying 'a' modifies the elements of 'x' that 'a' points to.

Some things to try
x = hnum(magic(5),'pointer') %a magic square that returns pointers when subscripted
a = x(5:7) %Creates a pointer to part of x
a(:) = sin(a) %This changes some values of x. note: a = sin(a) returns a double
a(1:end) = 500 %Subscripting subscript handles is also valid

Most of the functions of both classes were generated using a macro function. This was done to save time, as there are 100+ functions to overload. Because of this, not all functions allow as many inputs as their builtin versions. Some of the builtin functions were left out because they needed more than 2 inputs. See the two files in the 'Macro' directory for more information.

Watch out for memory leaks. Always delete an hnum object before replacing it.
x = hnum(1)
a = x(a)
x = 5 % This does not delete what 'x' used to be. Use delete(x) before.
a % 'a' keeps the previous x in memory even though you can't access it.

Cite As

Jon Danisch (2024). Pointers and subscript pointers (https://www.mathworks.com/matlabcentral/fileexchange/30223-pointers-and-subscript-pointers), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2010b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Programming Utilities in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes

Added reshape(), let(), sub()
Subscripthandles can now be subscripted to return another subscripthandle. ex:
x = hnum(magic(10));
a = x(:,1:5);
b = sub(a,'1:5',:); %points to x(1:5,1:5)