File Exchange

image thumbnail

User Defined Constants

version 1.0 (8.33 KB) by

Define your own special constants

0 Downloads

Updated

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.

Comments and Ratings (1)

sal

sal (view profile)

MATLAB Release
MATLAB 7.5 (R2007b)
Tags Add Tags

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Win prizes and improve your MATLAB skills

Play today