User Defined Constants

Define your own special constants
719 Downloads
Updated 25 Jan 2012

View License

Did you ever want the ability to define a special constant that is seen by and used in all of your functions, without needing to create global variables?

For example, suppose you used the golden ratio often in your work. Rather than creating a global variable named phi, or being forced to pass a variable around as an argument to your functions, I'll just use defcon to do the work for me.

>> defcon('phi',(1+sqrt(5))/2)

Here, I used defcon to create a new function called phi on my search path, that acts like the ones and zeros functions.

>> format long g
>> phi
ans =
1.61803398874989
>> phi(1,2)
ans =
1.61803398874989 1.61803398874989

phi is now a matlab function, that can be used inside other functions without any further effort. In fact, phi even has help defined, done automatically by defcon.

>> help phi
phi - User Defined Constant:

phi(N) is an N-by-N matrix filled with 1.6180339887498949.

phi(M,N) or phi([M,N]) is an M-by-N matrix of 1.6180339887498949.

phi(M,N,P,...) or phi([M N P ...]) is an M-by-N-by-P-by-...
array of 1.6180339887498949.

phi(SIZE(A)) is the same size as A and all 1.6180339887498949.

phi with no arguments is the scalar 1.6180339887498949.

see also: ones, zeros, nan

This means that from now on, the value of phi is defined to any function or script you will use. Because phi is now a function on your search path, it will also be available to you the next time you start MATLAB too. Of course, you must still be careful, as if you name a variable phi, matlab will find the variable first.

Deletion of a defined constant is easy enough too. The new function will be stored in the same directory that defcon resides in.

>> delete(which('phi'))

See that now phi is gone from my system.

>> phi
Undefined function or variable 'phi'.

The usual caveats apply here. Be careful in creating the name of a constant that is also the name of an existing matlab function or command. And if you already have a variable with that name, again there will be a problem.

Cite As

John D'Errico (2024). User Defined Constants (https://www.mathworks.com/matlabcentral/fileexchange/34770-user-defined-constants), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2007b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Files and Folders in Help Center and MATLAB Answers
Tags Add Tags

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.0.0.0