0% found this document useful (0 votes)
113 views

Introduction To Programming in Matlab: - M-File Scripts - M-File Functions

The document discusses MATLAB scripts and functions. It explains that scripts allow commands to be saved and repeatedly executed, while functions can accept inputs and return outputs. Scripts store variables in the base workspace, while functions have their own internal workspace. The document provides examples of simple scripts that solve equations and plot functions, and demonstrates the anatomy of a MATLAB function including the function definition line, help text, and function body. It also discusses the differences between scripts and functions, and how to use input and output arguments in functions.

Uploaded by

rayan alkurdi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Introduction To Programming in Matlab: - M-File Scripts - M-File Functions

The document discusses MATLAB scripts and functions. It explains that scripts allow commands to be saved and repeatedly executed, while functions can accept inputs and return outputs. Scripts store variables in the base workspace, while functions have their own internal workspace. The document provides examples of simple scripts that solve equations and plot functions, and demonstrates the anatomy of a MATLAB function including the function definition line, help text, and function body. It also discusses the differences between scripts and functions, and how to use input and output arguments in functions.

Uploaded by

rayan alkurdi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lecture 6

Chapter 4

Introduction to programming in
MATLAB

4.1 Introduction
So far in these lab sessions, all the commands were executed in the Command Window.
The problem 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:

1. 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 Scripts
• M-File Functions

4.2 M-File Scripts


A script file is an external file that contains a sequence of MATLAB statements. Script
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.

1
Lecture 6

4.2.1 Examples
Here are two simple scripts.

Example 1

Consider the system of equations:

3x + 3y + 4z
2x + 3y + 3z
Find the solution x 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 = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b

• Save the file, for example, example1.m.


• Run the file, in the command line, by typing:

>> example1
x =
-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:

2
Lecture 6
>> edit
or
>> edit filename.m

to open filename.m.

Example 2

Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 ∗


cos(x), in the interval 0 ≤ x ≤ 2π. This example has been presented in previous
Chapter. Here we put
the commands in a file.

• Create a file, say example2.m, which contains the following commands:

x=
0:pi/100:2*
pi; y1 =
2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,’--’,x,y2,’-
’,x,y3,’:’) xlabel(’0 \leq x \leq
2\pi’) ylabel(’Cosine
functions’)
legend(’2*cos(x)’,’cos(x)’,’0.5*cos
(x)’) title(’Typical example of
multiple plots’) axis([0 2*pi -3
3])
• Run the file by typing example2 in the Command Window.

4.2.2 Script side-effects


All variables created in a script file are added to the workspace. This may have
undesirable effects, because:

• Variables already existing in the workspace may be overwritten.


• The execution of the script can be affected by the state variables in the
workspace.

As a result, because scripts have some undesirable side-effects, it is better to


code any complicated applications using rather function M-file.

3
Lecture 6

4.3 M-File functions


As mentioned earlier, functions are programs (or routines ) that accept input
arguments and return output arguments. Each M-file function (or function or M-
file for short) has its own area of workspace, separated from the MATLAB base
workspace.

4.3.1 Anatomy of a M-File function


This simple function shows the basic parts of an M-file.

function f = factorial(n) (1)


FACTORIAL(N) returns the factorial of N. (2)
Compute a factorial value. (3)

f = prod(1:n); (4)

The first line of a function M-file starts with the keyword function. It gives the
function name and order of arguments. In the case of function factorial, there
are up to one output argument and one input argument. Table 4.1 summarizes
the M-file function.
As an example, for n = 5, the result is,

>> f =
factorial(5
)f =
120
Table 4.1: Anatomy of a M-File function

Part no. M-file element Description


(1) Function Define the function name, and the
definition number and order of input and
line output arguments
(2) H1 line A one line summary description
of the program, displayed when you
request Help
(3) Help text A more detailed description of
the program
(4) Function body Program code that performs
the actual computations

Both functions and scripts can have all of these parts, except for the function
definition line which applies to function only.
4
Lecture 6

In addition, it is important to note that function name must begin with a


letter, and must be no longer than than the maximum of 63 characters.
Furthermore, the name of the text file that you save will consist of the function
name with the extension .m. Thus, the above example file would be factorial.m.
Table 4.2 summarizes the differences between scripts and functions.

Table 4.2: Difference between scripts and functions


Scripts Functions
- 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 function.
with other scripts
- Are useful for automating - Are useful for extending the MATLAB
a series of commands language for your application

5
Lecture 6

4.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


C=FtoC(F) One input argument and

Three inputs and one output


Two inputs and two outputs

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 ways.

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 scored in three games.
The point from each game are assigned to a variable
by using the ‘input’ command.
Lecture 6
6
game1 = input(’Enter the points scored in the first game ’);
game2 = input(’Enter the points scored in the second game
’); game3 = input(’Enter the points scored in the third
game ’); average = (game1+game2+game3)/3

The following shows the command prompt when this script file (saved as
example3) is executed.

>> 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 assign string to a variable. For more
information, see MATLAB documentation.
A typical example of M-file 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 exe- cuted. In addition to this automatic display, MATLAB has
several commands that can be 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 4.4).

Table 4.4: di

. Simple to use.
. Provide limited control over the appearance of output

. Provide total control over the appearance of output

You might also like