A single MATLAB command typically has the form:
result = function ( value )where function represents the name of some function, value represents the input to the function, and result represents the output of the function.
In the above example, spaces may be inserted at will around any of the "tokens", or the line might be squeezed tight. Spaces could not be inserted between individual letters of the names, of course.
A function may have no input arguments, just one, or several. If it has no input arguments, the parentheses are dropped entirely. If it has multiple input arguments, then commas are used to separate them.
result = function result = function ( arg1 ) result = function ( arg1, arg2, arg3 )
A function may have no output arguments, just one, or several. If it has no output arguments, then the equals sign is not used. If it has more than one output argument, they are grouped with square brackets.
function ( a, b, c ) x = function ( a, b, c ) [ x, y, z ] = function ( a, b, c )
Most functions return one or more output arguments. The value of these output arguments will be printed automatically unless the command line terminates with a semicolon. The first command will print, and the second will not:
x = function ( a, b, c ) x = function ( a, b, c );
A series of short commands may be placed on a single line of text as long as they are separated by commas. The output of every command will be printed unless the string of commands is terminated by a semicolon:
y = f ( x ), z = f ( w ), q = f ( p );
If a command is too long to fit on a single line, it may be extended over several lines by ending each partial line with an ellipsis:
sum = a + b + c + d + ... e + f + g + h + ... i + j
There is a small inconsistency in this rule. If you are entering a matrix, then you are allowed to enter one row per line while skipping the ellipsis (and the semicolon that would normally indicate the end of a row). Thus, the following "economical" command:
A = [ 1 2 3 4 5 6 ]is equivalent to:
A = [ ... 1, 2, 3; ... 4, 5, 6 ]
MATLAB includes several constants that can be invoked by name:
Name | Meaning |
---|---|
eps | The machine precision number |
Inf | Infinity |
i | The square root of -1 |
j | The square root of -1 |
NaN | "Not a Number" |
pi | 3.14159265... |
realmax | The largest real number; |
realmin | The smallest positive real number; |
Since i and j are compulsively used by programmers as loop indices, the fact that MATLAB expects them to represent the imaginary unit is a classic bad idea that will automatically generate more errors than we need in this world.
The basic arithmetic operators used in MATLAB include:
Symbol | Meaning |
---|---|
+ | Addition |
- | Subtraction |
* | Matrix multiplication |
.* | Elementwise multiplication |
/ | Matrix "division" |
./ | Elementwise division |
\ | Matrix "division": A\b means A-1*b |
.\ | Elementwise division |
^ | Matrix exponentiation |
.^ | Elementwise exponentiation |
' | Matrix conjugate transpose |
.' | Matrix unconjugated transpose |
The basic arithmetic functions available in MATLAB include:
Name | Meaning |
---|---|
abs | absolute value |
acos | inverse cosine |
angle | the angle or argument of a complex number |
asin | inverse sine |
atan | inverse tangent |
atan2 | inverse tangent of (y,x) |
ceil | round to integer, towards +infinity |
conj | the conjugate of a complex number |
cos | cosine |
cosh | hyperbolic cosine |
cot | cotangent |
csc | cosecant |
exp | exponential |
fix | round to integer, towards 0 |
floor | round to integer, towards -infinity |
imag | the imaginary part of a complex number |
log | natural logarithm |
log2 | logarithm base 2 |
log10 | logarithm base 10 |
mod | remainder after division, mod(x,y) has same sign as x |
real | the real part of a complex number |
rem | remainder after division, rem(x,y) has same sign as y |
round | round to nearest integer |
sec | secant |
sign | the sign function |
sin | sine |
sinh | hyperbolic sine |
sqrt | square root |
tan | tangent |
tanh | hyperbolic tangent |
MATLAB does not have a special logical data type. However, functions, expressions and variables with a "logical" value, which actually have a numeric value, use the following convention:
Numeric Value | Meaning |
---|---|
0 | False |
1 | True |
nonzero | True |
The logical operators used in MATLAB include:
Symbol | Meaning |
---|---|
& | logical AND |
| | logical OR |
~ | logical complement or NOT |
xor | Exclusive OR |
The basic logical functions include:
Symbol | Meaning |
---|---|
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
== | equal to |
~= | not equal to |
Other logical functions include:
Symbol | Meaning |
---|---|
all ( X ) | All entries of X are nonzero; |
any ( X ) | Any entry of X is nonzero |
Certain operations can be applied to a vector:
Symbol | Meaning |
---|---|
v+w | the vector of sums of entries of v and w |
v*w' | the scalar product of row vectors v and w |
v'*w | the outer product of row vectors v and w |
v.*w | the vector of pairwise products of entries of v and w |
Certain functions can be applied to a vector:
Symbol | Meaning |
---|---|
v' | the transpose of v |
find(v) | returns the indices of nonzero (or TRUE) entries of v |
max(v) | the maximum entry of v |
min(v) | the minimum entry of v |
prod(v) | the product of the entries of v |
sum(v) | the sum of the entries of v |
Certain operations can be applied to a matrix:
Symbol | Meaning |
---|---|
A' | the transpose of A |
A+B | the elementwise sum of A and B |
A*B | the (standard) product of A and B |
A.*B | the elementwise product of A and B |
A^2 | the square of A |
A.^2 | the elementwise square of A |
Certain functions can be applied to a matrix:
Symbol | Meaning |
---|---|
det(A) | the determinant of (the square matrix) A |
find(A) | returns the row and column indices of nonzero (or TRUE) entries of A |
inv(A) | the inverse of (the square matrix) A |
max(A) | a row vector containing the maximum of each column |
max(max(A)) | the maximum entry of A |
min(A) | a row vector containing the minimum of each column |
min(min(A)) | the minimum entry of A |
A MATLAB function typically has three kinds of variables,
By default, local variables do not exist before the function is invoked. Any value they have must be assigned during the execution of the function, and that value is lost when the function is exited.
In some cases, it may be desirable to change the behavior of a local variable, so that, for instance, it has a value that "persists" between calls of the function, or it has a value that can be "seen" by some other routines, or even altered by other routines.
In FORTRAN, some variables may be declared with the "save" attribute. In C, the corresponding idea is called a "static" variable. In both languages, the intent is that once certain variables have been brought into existence by calling a routine, the memory associated with those variables is kept throughout the execution of the entire program. When the function that created these variables is exited, the variables stay around; if the function is invoked again, it recovers the variables with their current values.
To achieve this behavior in MATLAB, a variable must be declared "persistent", as in
persistent x persistent y, z
Here is an example program that uses a persistent variable. On each call, it returns the sum of every argument with which it has been invoked:
function total = grudge ( flag, x ) persistent my_sum; if ( flag ) my_sum = 0; else my_sum = my_sum + x; end total = my_sum;Presumably, a user of the routine would be told that the first call to my_sum should be with flag=1, so that my_sum can be initialized. Thereafter, the routine can be called repeatedly with flag=0, and each time the input argument x will be added to the current running total.
In some cases, it may be desired not to burden the user with having to pass in a flag to initialize the variables. It's not something users are good at, after all. Instead, the model might be that the internal variables will "know" whether they have been set up yet or not. A reasonable way to do this is to ask for the "size" of the variable. If a value has never been assigned to it, then its size will be zero.
function total = reverse ( fred ) persistent flip; if ( size ( flip ) == 0 ) flip = 1; end total = fred + flip; flip = 1 - flip;Here, the intent is that flip is 1 on calls 1, 3, 5, ..., and 0 on calls 2, 4, 6, and so on. But no external information is needed to properly initialize the value.
In FORTRAN77, a device called a COMMON block allowed different routines to access the same variables, without requiring transmission through the argument list. In FORTRAN90, this can be done using MODULES. In C, data can be shared among routines that are in the same source code file by declaring the data in the beginning of the file, "outside" of the text of any particular routine.
In each case, the desire is that the memory associated with certain variables be easily accessible by name. The corresponding feature in MATLAB is a "global" variable. If a variable is declared global, then its value is shared among all routines that invoke the same declaration. The value of the global variable persists throughout the execution of the program.
Thus, in order for the functions bob.m and carol.m to share the value of the variable ted, they would both need to include the declaration
global tedThen a single memory location ted is created and shared by the two programs. Changes to ted by one routine will be visible to the other routine.
Control structures are used to control the execution of statements. The common control structures include for, if and while.
A simple example of a FOR loop:
sum = 0; for ( i = 1 : 5 ) sum = sum + i^2; endIn this case, the loop is executed with i having the values 1, 2, 3, 4, and 5.
To specify a loop increment that is not 1, use notation like the following:
for ( i = 1 : 10 : 3 )In this case, the loop is executed with i having the values 1, 4, 7, 10. Similarly, a decreasing loop index can be achieved by the form:
for ( i = 10 : 1 : -3 )which happens to go through the same values, but in reverse order.
In some cases, you may want to skip the rest of a particular cycle of the loop, without actually terminating the loop. This can be done using the continue statement:
sum = 0; for ( i = 1 : 10 ) if ( x(i) == 0 ) continue end sum = sum + 1 / x(i); end
On the other hand, there are cases (such as a search) where you may suddenly want to terminate the loop. This can be done using the break statement:
location = 0; for ( i = 1 : 10 ) if ( x(i) == 17 ) location = i; break; end end
A simple example of an IF statement:
if ( mod ( n, 2 ) == 0 ) n = n / 2; end
A more elaborate example of an IF/ELSE statement:
if ( mod ( n, 2 ) == 0 ) n = n / 2; else n = 3 * n + 1; end
A more elaborate example of an IF/ELSEIF/ELSE statement:
if ( mod ( n, 3 ) == 0 ) n = n / 3; elseif ( mod ( n, 3 ) == 1 ) n = 4 * n + 1; else n = 4 * n + 2; end
Note that elseif is not the same as else if! The elseif command stays at the level of the opening if, and considers an alternate possibility:
if ( x < 0 ) there is no square root elseif ( x == 0 ) the square root is zero endThe else if command is really two commands, an else at the level of the opening if, and a new if which takes us down a level. Note, in particular, that there will have to be at least two end statements following!
if ( x < 0 ) there is no square root else if ( x == 0 ) the square root is zero end endwhich is equivalent to:
if ( x < 0 ) there is no square root else if ( x == 0 ) the square root is zero end endThe problem is that elseif and else if look identical to the programmer, but not to MATLAB!
A simple example of a WHILE loop:
n = 98; log_base_2 = 0; while ( n > 1 ) n = n / 2; log_base_2 = log_base_2 + 1; end
To make a "WHILE forever" loop, use a nonzero value, typically 1, as the "condition" to be checked:
n = 98; log_base_2 = 0; while ( 1 ) n = n / 2; log_base_2 = log_base_2 + 1; if ( n == 0 ) break; end endA break statement allows you to exit the while loop. A continue statement allows you to skip the remainder of the while loop, and begin the next iteration.
The simplest input requirement occurs when you're running a Matlab script interactively, and you want to ask the user to enter a number that specifies what to do next, such as how many iterations to perform, or what error tolerance to impose. To do this, one can use the input function, which takes a prompt string as its input argument, and returns as its value the number (or vector or matrix) that the user typed in.
iter_max = input ( 'Enter the maximum number of iterations.' );
In some cases, it is convenient or even necessary that information in a file be read into MATLAB. (In fact, it is also possible for MATLAB to write out information into a file, which can be read back in at a later time, using the save command...). In the simplest case, the user has prepared an ASCII text file containing one number, or one line of text containing several numbers, or several lines of text each containing the same number of values. Assuming the file is called fred.txt, say, then the user can have MATLAB read the values in the file and assign them to a variable with a command like
array = load ( 'fred.txt' )
MATLAB also allows the user to open an existing file with fopen, extract information using fread, fscanf, fgetl and fgets, and then close the file with fclose. The form and use of these commands is quite similar to their C ancestors.
Most MATLAB statements are assignments or computations that have a result. By default, this result is printed once it's computed. This means that simple MATLAB codes don't need any fancy output statements. Executing the statements
a = 4 b = sqrt ( a ) c = 1 / ( a + b )will result in the printout of the values 4, 2, and 1/6. In fact, if you want to check the value of a variable, all you have to do is enter its name:
dwill cause the value of d to be displayed.
This default printing operation always includes the name of the variable in the output, as well as an "=" sign and possibly one or two blank lines. If you simply want to see the value of a variable or expression, you can use the disp function to do so:
disp ( 4 ) disp ( sqrt ( a ) ) disp ( 1 / ( a + b ) ) disp ( 'Hi there, everyone!' )These commands will, in each case, print out the unlabeled value.
While this default printing can be handy, sometimes you don't want to see it, especially inside of functions or iterative calculations. Any line that produces a result can be "silenced" by terminating it with a semicolon. Thus, the following commands will not produce any printed output:
a = 5; b = mod ( 32, 7 ); c = cos ( pi / 5 ) + sin ( pi / 5 );It's not so easy to shut up the disp command. Even if you type
disp ( 4 );the disp command will still print out the value.
One way to control the style of output from MATLAB is to use the fprintf command. This command has the logical form
fprintf ( unit, string, arg1, arg2, ... )To print directly to the screen, the value of unit should be 1. The string contains the form of the output line, except that positions where a variable's value is to appear are marked by a placeholder that begins with a percent sign, and a new line, or carriage return, is indicated by the string '\n'. The corresponding variables themselves are then listed as arg1 and so on.
For instance, you might print
fprintf ( 1, 'The results follow:\n' ) fprintf ( 1, ' X + Y = %f\n', x + y ) fprintf ( 1, ' Caesar''s first name was %s.\n', pronomen ); fprintf ( 1, ' Today is %d and I am %d years old.\n', year, age );
For additional control, you may specify, for instance, the number of spaces to be used in printing out the variable:
fprintf ( 1, 'The results follow:\n' ) fprintf ( 1, ' X + Y = %12f\n', x + y ) fprintf ( 1, ' Caesar''s first name was %10s.\n', pronomen ); fprintf ( 1, ' Today is %4d and I am %2d years old.\n', year, age );
Integers are normally printed with the d marker, but "very large" integers will not be displayed in decimal form, but rather in scientific notation, no matter how hard you try.
For a program in which complex arithmetic is used for all arithmetic data types, the proper printing of a complex number through FPRINTF can be surprisingly difficult. Unless you redefine it, the name i will signify the imaginary unit, so you can use it to form complex expressions. I started with the following statements:
x = 1 + 2 * i fprintf ( 1, 'X = %f\n', x );but what prints out is simply "1". Even if you take a guess at the fix and try
fprintf ( 1, 'X = %f %f\n', x );you get nothing but "1". I tried other format specifiers, but got nowhere. As far as I could tell, there is no appropriate format string that will cause a complex number to be printed properly.
A correspondent, Alan Weiss, has let me know that the appropriate way to handle this problem is to use the Matlab command num2str to convert the complex number to a string, and then print it as as string:
x = 1 + 2 * i fprintf ( 1, 'X = %s\n', num2str ( x ) );and this, indeed, works.
Before finding out that useful piece of information, I assumed that I had to get the result I wanted using only the knowledge I had. Since the imaginary part of a complex number exists, and we can access it with the imag function, we could get a printout doing this:
x = 1 + 2 * i fprintf ( 1, 'X = %f %f\n', real ( x ), imag ( x ) );
Once you see that that actually works, it's time to celebrate by throwing in the plus sign and the "i":
x = 1 + 2 i fprintf ( 1, 'X = %f + %f i\n', real ( x ), imag ( x ) );and now you can decide whether you want to properly handle the case where the imaginary part is negative. (You'd like to avoid the ugly expression "1 + -2 i", for instance.) Obviously, it's time to give up and use the num2str function unless you have a really good reason not to!
MATLAB "remembers" all the variables that it encounters. Sometimes this can be a disadvantage. During a lengthy session, or in a situation where a number of independent functions are invoked, it may be the case that the pre-existence of a given variable causes a normally well-behaved function to fail. For instance, you might think that the following statements are essentially the same:
x = zeros(1,5); x(1:5) = 0;
But in the first case, any previous meaning that x had is discarded, and x is guaranteed to be a 1 by 5 vector of 0's. In the second case, we'll get an error message if a variable called x already exists, but cannot legally be addressed as a vector. Moreover, if a vector x does already exist, then its entries after entry 5 are still around, which may cause some nasty surprises.
This is only one reason why it might be nice to "clear out" one, several, or all old variables at certain points in a script, or an interactive session. Thus, typing
clear xdiscards any variable called x. Typing
clear x y zclears three variables out at once, and typing
cleardiscards all currently stored variables.
I'm not sure why you'd want to do this, but typing
exitinteractively, or in a function, terminates MATLAB. The only reason I want to know this is that I mistakenly had an exit statement which I thought was a break statement (this was because I was "translating" between MATLAB and FORTRAN90). I thought I had a serious bug in the code somewhere, because it kept crashing, and hard, but all it was was a simple little unintended exit.
You can return to the HTML web page.