Chapter 4
Introduction to programming in
MATLAB
4.1 Introduction
these lab sessions, all the commands were executed in the Command Window.
is that the commands entered in the Command Window cannot be saved
and executed again for several times. Therefore, a different way of executing repeatedly
commands with MATLAB is
L. to create a file with a list of commands,
2. save the file, and
3. run the file
If needed, corrections or changes can be made to the commands in the file. The files that
are used for this purpose are called script files or scripts for short.
‘This section covers the following topics:
* M-File
cripts
* M-File Functions
4.2 M-File Scripts
A script file is an external file that contains a sequence of MATLAB statements. Seript
files have a filename extension .m and are often called M-files. M-files can be scripts that
simply execute a series of MATLAB statements, or they can be functions that can accept
arguments and can produce one or more outputs.4.2.1 Examples
Here are two simple scripts.
Example 1
Consider the system of equations:
ety +32
3r+3yt4z
2x + By 432
Find the solution 2 to the system of equations.
SoLuTion:
Use the MATLAB editor to create a file: File + New > M-file.
Enter the following statements in the file
A= (123,334,233);
b= (1: 1; 2];
x = A\D
Save the file, for example, example1.m.
Run the file, in the command line, by typing:
>> examplel
-0.5000
1.5000
-0.5000
When execution completes, the variables (A, b, and x) remain in the workspace. To see a
listing of them, enter whos at the command prompt,
Note: The MATLAB editor is both a text editor specialized for creating M-files and a
graphical MATLAB debugger. The MATLAB editor has numerous menus for tasks such as
saving, viewing, and debugging. Because it performs some simple checks and also uses color
to differentiate between various elements of codes, this text editor is recommended as the
tool of choice for writing and editing M-files,
‘There is another way to open the editor:
36>> edit
or
>> edit filenane.m
to open filename-n.
Example 2
Plot the following cosine functions, y; = 2cos(z), y2 = eos(z), and ys = 0.5 + cos(z), in the
interval 0 > £ = factorial (5)
te
120
Table 4.1: Anatomy of a M-File funetion
Part no. | M-file element | Description
w Function Define the fanetion name, and the
definition number and order of input and
line output arguments
@ HI ine ‘Tone Tine summary description
of the program, displayed when you
request Help
@ Trelp toxt ‘A more detailed description of
the program
@ Function body — | Program code that perforins
the actual computations
Both functions and scripts can have all of these parts, except for the function definition
line which applies to function only.
38In addition, it is important to note that function name must begin with a letter, and
thermore, the name of the
nut be no longer than than the maximum of 63 characters. F
text file that you save will consist of the function name with the extension .x. Thus, the
above example file would be factorial.m
Table 4.2 summarizes the differences between scripts and functions.
Table 4.2: Difference between seripts and functions
on:
Scripts Fu
= Do not accept input ~ Can accept input arguments and
arguments or return output | return output arguments.
arguments
- Store variables in a - Store variables in a workspace
workspace that is shared | internal to the funetion.
with other scripts
- Are useful for automating | - Are useful for extending the MATLAB
a series of commands language for your application4.3.2. Input and output arguments
As mentioned above, the input arguments are listed inside parentheses following the function
name, The output arguments are listed inside the brackets on the left side. They are used
to transfer the output from the function file, The general form looks like this
function [outputs] = function_name(inputs)
Function file can have none, one, or several output arguments. Table 4.3 illustrates some
possible combinations of input and output arguments,
‘Table 4.3: Example of input and output arguments
function C=FtoC(F) One input argument and
one output argument
function area=TrapArea(a,b,h) ‘Three inputs and one o
function [h,d]-motion(v,angle) Two inputs and two ou
4.4 Input to a script file
When a script file is executed, the variables that are used in the calculations within the file
must have assigned values. The assignment of a value to a variable can be done in three
1. The variable is defined in the script file
2. The variable is defined in the command prompt.
3. ‘The variable is entered when the script is executed.
We have already seen the two first cases. Here, we will focus our attention on the third one.
In this case, the variable is defined in the script file. When the file is executed, the user is
prompted to assign a value to the variable in the command prompt. This is done by using
the input command. Here is an example
This script file calculates the average of points
i scored in three games
i The point from each game are assigned to a variable
by using the “input” conmand
gamel = input(*Enter the points scored in the first game *);
40game2 = input(’Enter the points scored in the second game ’);
game3 = input(’Enter the points scored in the third game ’);
average = (gane1*gane2#gane3)/3
The following shows the command prompt when this script file (saved as example) is
exeouted
>> example3
>> Enter the points scored in the first game 15
>> Enter the points scored in the second game 23
>> Enter the points scored in the third game 10
average =
16
The input command can also be used to a
see MATLAB documentation
jign string to a variable. For more information,
A typical example of M-fle function programming can be found in a recent
paper which
related to the solution of the ordinary differential equation (ODE) [12
4.5 Output commands
As discussed before, MATLAB automatically generates a display when commands are 3
cuted. In addition to this automatic display, MATLAB has several comman
used to generate displays or outputs,
‘Two commands that are frequently used to generate output are: disp and fprintf
The main differences between these two commands can be summarized as follows (Table
44)
Table 4.4: disp and fprintf commands
Simple to use.
Provide limited control over the appearance of output
fprintf . Slightly more complicated than disp.
Provide total control over the appearance of output4.6 Exercises
1. Liz buys three apples, a dozen bananas, and one cantaloupe for $2.36. Bob buys a dozen
apples and two cantaloupe for $5.26. Carol buys two bananas and three cantaloupe
for $2.77. How much do single pieces of each fruit cost?
2. Write a function file that converts temperature in degrees Fahrenheit (*F) to degrees
Centigrade (°C), Use input and fprintf commands to display a mix of text and
numbers, Recall the conversion formulation, C = 5/9 « (F — 32).
3. Write a user-defined MATLAB function, with two input and two output arguments
that determines the height in centimeters (cx) and mass in kilograms (kg)of a person
from his height in inches (in.) and weight in pounds (1b).
) Determine in SI units the height and mass of a 5 £f.15 in. person who weight 180
hb.
(b) Determine your own height and weight in SI units.
a2