Chapter 2: Introduction To MATLAB Programming: January 2017
Chapter 2: Introduction To MATLAB Programming: January 2017
net/publication/323237076
CITATIONS READS
0 1,870
1 author:
Ronald Pascual
De La Salle University
24 PUBLICATIONS 12 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
All content following this page was uploaded by Ronald Pascual on 17 February 2018.
2.3 Introduction
This chapter gives a brief introduction to MATLAB programming fundamentals to prepare us for signal
processing tasks that we will encounter in the succeeding chapters in this laboratory course. For
instance, there are times that we need to write a program comprising of an ordered list of signal
processing tasks that we can execute automatically without human intervention, or we can repeatedly
apply to different input signals. Programs in MATLAB are simply called M-files, and can either be a script
or a function. M-files have a filename extension of *.m.
In particular, this chapter will cover basic structures of M-file scripts and functions, branching
commands or conditional statements such as the if-else, definite and indefinite loop commands such as
the for and the while loops, respectively. Although not really a prerequisite, background knowledge in
basic C-language programming and the likes would be an advantage for you to easily pick up the
materials presented in this chapter.
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 18
commands within a script, would usually be embedded in the script code. The variables created within a
script would also be available in the MATLAB workspace, much like global variables.
To create a new M-file script, click on the <New Script> button from the MATLAB toolbar.
A new window called the Editor window will appear. A screen shot of the Editor window is shown in Fig.
2.1 below. Note that as you press <Enter>, the editor window provides automatic line numbering as can
be seen on the left side of the window for the purposes of easy debugging. You may also add comments
in MATLAB by preceding the text comment by the percent sign (%), as in Line 1 of Fig. 2.1.
Comments may be inserted in MATLAB using the percent sign (%). That is, any text that follows
the percent sign are regarded to by MATLAB simply as remarks, and are not part of the commands to
execute within the script.
Example 2.1
Suppose we want to write an M-file script that would accomplish the following sequence of tasks:
1.) Create a ramp or linearly increasing discrete-time signal with 20 samples and with amplitude
ranging from 0 to 1.
2.) Create a 5-cycle sawtooth signal by concatenating the ramp signal in part (1).
3.) Plot the sawtooth signal created in part (2) with proper annotations.
A script that may accomplish the above tasks is shown in Fig. 2.2 below.
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 19
Fig. 2.2. script_2_1.m (Script for Example 2.1)
Create the script shown in Fig. 2.2 and save it as script_2_1.m. Then run your script either by
clicking the run button from the Editor Window toolbar, or by typing the script filename in the
Command Window:
>> script_2_1
If you are successful in doing the above tasks, you should be able to see a sawtooth signal shown in Fig.
2.3 below.
Exercise 2.1
Write an M-file script that generates and plots a 4-cycle, 120-sample discrete-time square wave signal as
shown in Fig. 2.4 below:
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 20
Fig. 2.4. Output waveform for Exercise 2.1 (square wave).
Save your script as exer_2_1.m. List down your script commands on the space provided below:
QUESTION 2.1:
After running your script, are the variables created inside your script also available in the workspace?
Show a proof and briefly explain for your answer.
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 21
MATLAB functions use a descriptive header or a function declaration line containing the
following information: Function name, list of inputs, and list of outputs. The general format of a function
header or declaration line is given below:
function [output_variable]=function_name(input_variable);
To create a new M-file function, you may also click on the <New Script> button from the MATLAB
toolbar and then start by typing the function declaration on the first line of the Editor window.
Example 2.2
Say we want to write an M-file function that accepts two numbers as inputs, and then computes and
returns their sum and average. A possible way of writing the function that would accomplish the
aforementioned task is shown below in Fig. 2.5. We suggest that you type the function in a new Editor
window, and then save your M-file function as func_2_2.m.
Note how the function header starts with the keyword ‘function’ followed by the respective
output variables for the sum and the average (‘s’ and ‘ave’), the equal sign(‘=’), the function name
(‘func_2_2’), and the input variables representing the two input numbers (‘n1’ and ‘n2’). Note also that
output variables are enclosed by square brackets [ ], while input variables are enclosed by parenthesis ().
Lines 3 and 4 in the function compute the sum and the average, respectively, and store them in the
respective variables ‘s’ and ‘ave’ as declared in the function header.
It is important that all output variables be assigned with the correct values to return before the
end of the function.
We may also note from Fig. 2.5 that line 2 is used for generating the function Help text. To verify how
this works, you may invoke the help command from the command window as follows:
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 22
Exercise 2.2
Modify the M-file script_2_1.m given in Fig. 2.2 and turn in into an M-file function such that the number
of samples per cyle is now a user input, and the output is a vector containing the samples of the 5-cycle
sawtooth signal. The function must also plot the output signal. Save your M-file function as exer_2_2.m.
For example, if the user wants to have 10 samples per cycle, we may invoke the following
command in the command window:
>> [signal]=exer_2_2(10);
Fig. 2.6. Signal plot for function exer_2_2.m with input = 10.
Make a list of your commands for exer_2_2.m in the space provided below.
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 23
if expression,
statements
else
statements
end
The ‘expression’ in Fig. 2.7 is a logical expression using a logical operator such as equal (==), greater than
or equal (>=), less than or equal (<=), not equal (~=), AND (&), and OR(|).
Note that the basic if-else statement lets you choose from only two sets of statements. A
modification of the basic if-else statement however lets you choose from more than two sets of
statements by inserting more alternate choices through the use of elseif keyword. The if-elseif-else
format is shown in Fig. 2.8 below.
if expression,
statements
elseif
statements
elseif
statements
else
statements
end
Another alternative branching command is the ‘switch’ statement. We may use the ‘switch’
statement if we want to branch or to switch to several known cases or options. The general form of the
switch statement is shown below in Fig. 2.9.
switch switch_expr
case case_expr1,
statements
case case_expr2,
statements
...
otherwise,
statements
end
Example 2.3
Let’s say for example that we want to write a function that returns the equivalent grade for an input
score according to the following table:
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 24
Input Score Equivalent Grade
96-100 4.0
87-95 3.0
78-86 2.0
70-77 1.0
0-69 0.5
The function named func_2_3.m (shown below in Fig. 2.10) will do the required task.
An example of how the function func_2_3.m responds to an input score is shown below:
>> g=func_2_3(85)
g =
2
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 25
In MATLAB, the easiest way to create a prespecified loop is to use the ‘for’ statement. The
‘for’statement repeats a statement or a block of statements a predetermined number of times as
indicated by the expression for the incrementing index variable. The general form of a ‘for’ statement is
given below in Fig. 2.11.
If what we need is an indefinite loop, we can create it in MATLAB by employing the ‘while’
statement. The ‘while’ statement repeats a statement or a block of statements as long as a condition,
which is a logical expression, remains true. The general form of a ‘while’ statement is given below in Fig.
2.12.
while expression,
statements
end
Another command that may become useful when dealing with loops is the ‘break’ statement. A
‘break’ statement executed within a loop will immediately terminate the execution of a loop, and will
allow you to immediately exit a ‘for’ or a ‘while’ loop.
If you are caught up in an infinite loop, hitting <Ctrl + C> or <Ctrl + Break> will immediately
terminate the loop execution.
Example 2.4
Suppose we want a function that accepts an integer N, and then returns an N-by-N matrix with the
following pattern:
1 0 0 ... 0
1 2 0 ... 0
1 2 3 ... 0
: : : : :
1 .. .. .. N
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 26
Using a ‘for’ loop, we may accomplish the task by writing the function ‘func_2_4.m’ as shown below in
Fig.2.13.
Note from line 3 in Fig. 2.13 that the index variable ‘k’ is incremented from 1 through N. An example of
how the function ‘func_2_4.m’ responds to an input integer is given in Fig. 2.14 below.
>> A=func_2_4(5)
A =
1 0 0 0 0
1 2 0 0 0
1 2 3 0 0
1 2 3 4 0
1 2 3 4 5
Example 2.5
Now suppose we want to rework Example 2.4, this time using a ‘while’ loop. This is accomplished by the
function ‘func_2_5.m’ shown in Fig. 2.15 below.
Try avoiding ’for’ and ‘while’ loops because they can significantly increase the computation or
execution time for your MATLAB command or M-file. If you replace loops by vector or matrix operations,
your MATLAB program would be much more efficient or faster to execute.
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 27
Exercise 2.3
Consider the Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21, ….
Observe that from 3rd term onwards, the value of each term is the sum of the previous two terms. For
instance, the 5th term is the sum of the 3rd and the 4th terms, that is, 5=2+3.
Using a ‘for’ or a ‘while’ loop, write an M-file function that accepts an input number N, and then returns
the Nth term of the Fibonacci series given above. Save your M-file as ‘exer_2_3.m’.
For example, if we desire to compute the 6th term of the Fibonacci series, our command and MATLAB’s
response would be:
>> exer_2_3(6)
ans =
8
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 28
MATLAB Code/Notes:
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 29
Results and Conclusion:
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
DSP Lab Manual – Ronald M. Pascual & FEU Institute of Technology Page 30