Code covered by the BSD License

### Highlights from User Defined Constants

Be the first to rate this file! 7 Downloads (last 30 days) File Size: 8.33 KB File ID: #34770

# User Defined Constants

### John D'Errico (view profile)

File Information
Description

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.

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.

Required Products Bioinformatics Toolbox
MATLAB release MATLAB 7.5 (R2007b)
Other requirements This tool will work on any recent version of matlab.

No tags are associated with this file.