MATLAB programs are stored as plain text in files having names that end with the extension ``.m''. These files are called, not surprisingly, m-files. Each m-file contains exactly one MATLAB function. Thus, a collection of MATLAB functions can lead to a large number of relatively small files.
One nifty difference between MATLAB and traditional high level languages is that MATLAB functions can be used interactively. In addition to providing the obvious support for interactive calculation, it also is a very convenient way to debug functions that are part of a bigger project.
MATLAB functions have two parameter lists, one for input and one for output. This supports one of the cardinal rules of MATLAB programming: don't change the input parameters of a function. Like all cardinal rules, this one is broken at times. My free advice, however, is to stick to the rule. This will require you to make some slight adjustments in the way you program. In the end this shift will help you write better MATLAB code.
When you are writing m-files you will usually want to have the text editor and MATLAB open at the same time. Since modern word-processors require lots of system RAM it may not even be possible or practical (if you are working on a stand-alone personal computer) for you to use a word-processor for m-file development. In this case a simple, text editor will be your only option.
function [output_parameter_list] = function_name(input_parameter_list)The first word must always be ``function''. Following that, the (optional) output parameters are enclosed in square brackets [ ]. If the function has no output_parameter_list the square brackets and the equal sign are also omitted. The function_name is a character string that will be used to call the function. The function_name must also be the same as the file name (without the ``.m'') in which the function is stored. In other words the MATLAB function, ``foo'', must be stored in the file, ``foo.m''. Following the file name is the (optional) input_parameter_list.
There can exactly be one MATLAB function per m-file.
Unlike other languages, the variables in the input_parameter_list should never be altered by the statements inside the function. Expert MATLAB programmers have ways and reasons for violating that principle, but it is good practice to consider the input variables to be constants that cannot be changed. The separation of input and output variables helps to reinforce this principle.
The input and output variables can be scalars, vectors, matrices, and strings. In fact, MATLAB does not really distinguish between variables types until some calculation or operation involving the variables is performed. It is perfectly acceptable that the input to a function is a scalar during one call and a vector during another call.
To make the preceding point more concrete, consider the following statement
>> y = sin(x)which is a call to the built-in sine function. If x is a scalar (i.e. a matrix with one row and one column) then y will be a scalar. If x is a row vector, then y will be a row vector. If x is a matrix then y is a matrix. (You should verify these statements with some simple MATLAB calculations.)
This situation-dependence of input and output variables is a very powerful and potentially very confusing feature of MATLAB. Refer to the ``addtwo.m'' function below for an example.
function addtwo(x,y) % addtwo(x,y) Adds two numbers, vectors, whatever, and % print the result = x + y x+yThe
addtwofunction has no output parameters so the square brackets and the equal sign are omitted. There is only one MATLAB statement,
x+y, in the function. Since this line does not end with a semicolon the results of the calculation are printed to the command window.
The first two lines after the function definition are comment statements. Not only do these statements describe the statements in the file, their position in the file supports the on-line help facility in MATLAB. If the first line of a MATLAB function definition is immediately followed by non-blank comment statements, then those comment statements are printed to the command window when you type ``help function_name". Try it with the addtwo function. MATLAB will print up until a blank line or an executable statement, whichever comes first. Refer to the Function prologues -- providing help section for more information.
To test your understanding of input and output variables, pass
the following definitions of x and y to the
(To save space the x and y variables are defined on the same
line. You can enter these variables on the same line, as shown,
or use separate lines.)
>> x = 2; y = 3; >> x = [2 3]; y = [4; 5]; >> x = eye(3,3); y = -2*eye(3,3); >> x = 'Sue'; y = 'Bob' >> x = 'Jane'; y = 'Bob'
Here is another simple function, traparea.m, with three input parameters and one output parameter. Since there is only one output parameter the square brackets may be omitted.
function area = traparea(a,b,h) % traparea(a,b,h) Computes the area of a trapezoid given % the dimensions a, b and h, where a and b % are the lengths of the parallel sides and % h is the distance between these sides % Compute the area, but suppress printing of the result area = 0.5*(a+b)*h;Note that there is a blank line between the comment statements that describe the function and the single comment statement that describes the calculation of area. The comment statement beginning ``Compute the area...'' will not be printed if you type ``help traparea''. Also note that there is no ``return'' statement needed. (There is a MATLAB return statement, but it is not needed here.) The output variable,
area, is defined in the first line of the file. The value assigned to
areais returned to the calling function or the command window.
Finally, here is another simple function, cart2plr.m, with two input parameters and two output parameters.
function [r,theta] = cart2plr(x,y) % cart2plr Convert Cartesian coordinates to polar coordinates % % [r,theta] = cart2plr(x,y) computes r and theta with % % r = sqrt(x^2 + y^2); % theta = atan2(y,x); r = sqrt(x^2 + y^2); theta = atan2(y,x);The comment statements have empty lines, but these will be printed if you type ``help cart2plr''.
A simple warning
>> d = b^2 - 4*a*c; >> if d<0 >> disp('warning: discriminant is negative, roots are imaginary'); >> endor a warning plus extra notification
>> d = b^2 - 4*a*c; >> if d<0 >> disp('warning: discriminant is negative, roots are imaginary'); >> else >> disp('OK: roots are real, but may be repeated'); >> endor, no secrets whatsoever
>> d = b^2 - 4*a*c; >> if d<0 >> disp('warning: discriminant is negative, roots are imaginary'); >> elseif d==0 >> disp('discriminant is zero, roots are repeated'); >> else >> disp('OK: roots are real and distinct'); >> endCareful inspection of the preceding statements reveals that
if x<0, disp('imaginary'); endNotice the comma between the
disp(...). Apparently the comma tells the MATLAB interpretter that the conditional test has ended. To my knowledge this is only place where a statement (OK, part of a statement) ends with a comma. It's just one of those quirks that true believers come to use without hesitation.
The preceding table lists the logical comparison operators used in MATLAB. Note that these operators can be used in assignment statements, as illustrated in this example
enough = xnew-xold < delta if ~enough stepSize = stepSize/2; endThe first statement assigns the value of the logical comparison to the variable ``
enough''. If the comparison on the right hand side evaluates to be true, then
enoughis given the value 1. If the comparison evaluates to be false, then
enoughis given the value 0. In the subsequent
enough = 1is true, and
enough = 0is false.
&& operator (read ``and'' operator) takes
two logical expressions and returns ``true'' if both expressions
are true, and ``false'' otherwise.
|| operator (read ``or'' operator) takes
two logical expressions and returns ``true'' if either of the
expressions are true, and ``false'' only if both expressions
are false. The possible outcomes of
|| operations are summarized in the following truth table.
~ operator (read ``not'') takes only one
logical expression and returns the opposite (negation) of
that expression. Consider the following code
a = 2; b = 3; asmall = a < b; % asmall is ``true'' if ~asmall disp('a is greater than b') endSince
ais less than
if ~asmallblock is not executed because
while expression do something endwhere ``expression'' is a logical expression. The ``do something'' block of code is repeated until the expression in the while statement becomes false.
Here is an example
i = 2; while i<8 i = i + 2 endExecuting the preceding block of code results in the following output to the command window
i = 4 i = 6 i = 8(The output has been adjusted to take up less space. MATLAB likes to sprawl its printout over several lines.) Note that no
fprintfstatement was needed in the preceding block because the
i = i + 2statement did not end in a semicolon.
sum = 0; for i=1:length(x) while i<10 sum = sum + abs(x(i)); end
[Preceding Section] [Master Outline] [Section Outline] [Next Section]