File Exchange

image thumbnail

CONST structure

version (11.7 KB) by Rody Oldenhuis
STRUCT with immutable fields

1 Download

Updated 10 Jun 2018

GitHub view license on GitHub

MATLAB's flexible nature is very convenient in most situations. However, this flexibility can also be the cause of hard-to-find bugs.
In many cases, it is desirable to have a data type which is CONST. That is, a datatype which cannot be changed after the first assignment. MATLAB has seen heavy criticism due to its lack of a CONST data type. Although the basic functionality of CONST variables can be achieved through a class with constant properties, that approach leaves much to be desired.

That is where this file comes in. It implements all the functionality of a basic, scalar MATLAB structure, but after a field has been added and assigned a value, that field can no longer be changed.

That means, it strikes a middle ground by offering the flexibility of adding fields dynamically, but disallowing *changing* of fields values.

A simple example session:

C = const; % empty const
C.myField = 'test'; % first assignment; OK
C.myField = 4; % ERROR!

Much more is possible; have a look at the function documentation inside const.m for more information.

If you find this work useful, please consider a donation:

Comments and Ratings (2)

sorry my fault, I changed your codes.
Now I changed it back and it works very good !!!

I tried your example and got the following error ???

>> C = const;
C.myField = 5;
Error: File: const.m Line: 58 Column: 1
Illegal use of reserved keyword "classdef".


Improved error handling a little bit
Refactored code for better extensibility

[linked to Github]

MATLAB Release Compatibility
Created with R2010a
Compatible with any release
Platform Compatibility
Windows macOS Linux