Вы находитесь на странице: 1из 100

Engineering System Design

ENGR10003

Programming for Engineering System Design 2


(ESD2)
Subject Notes

Author: Shanika Karunasekera

1
Module Outline

Module Overview

In this module of the subject, you will learn how to write programs to solve engineering system design
problems using MATLAB. MATLAB is a multi-paradigm numerical computing environment and fourth-
generation programming language.
The topics in this subject include:

Introduction: In this topic, you will get an introduction to computer programming and its use in engi-
neering system design. We will also look at MATLAB as a programming environment and learn
to write simple MATLAB programs that can take user input from the keyboard and display output
to the screen.

Calculation: In this topic, you will learn how to write programs that perform simple calculations.

Functions: In this topic, you will learn how to create self-contained modules, called functions, that can
then be put together to build a MATLAB program.

Selection: In this topic, you will learn how to make choices, also referred to as selection or branching
in MATLAB programs.

Repetition: In this topic, you will learn how to perform repetitive actions in a MATLAB program,
through looping.

Input-Output: In this topic you will learn how a MATLAB program can read data from files, write data
to files and generate plots.

Learning outcomes

On completion of this subject, students should be able to:

• Develop programming solutions to engineering design problems using the top-down design fol-
lowed by bottom-up implementation;

• Write computer programs to solve engineering design problems; and

• understand the role of computer programs in solving complex engineering problems

2
Assessment

This module will have two individual assignments, each worth 3 marks, and a project worth [insert
number] marks.

3
Contents

1 Introduction 8
1.1 What is a computer program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2 Role of computer programs in Engineering System Design . . . . . . . . . . . . . . . . 8
1.3 Motivating examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.1 Example 1: Chemical Process Alarm Generator . . . . . . . . . . . . . . . . . . 9
1.3.2 Example 2: Analog-to-Digital Converter . . . . . . . . . . . . . . . . . . . . . 10
1.3.3 Example 3: Parachute design problem. . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Why computer programs? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5 Computer Software, Hardware & Operating System . . . . . . . . . . . . . . . . . . . . 12
1.5.1 Software: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.2 Hardware: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.3 Operating System: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6 Programming languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Introduction to MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8 Programming with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.8.1 MATLAB instructions/commands . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.8.2 MATLAB interactive mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.8.3 First Program: Display a message on the screen . . . . . . . . . . . . . . . . . . 15
1.8.4 Running MATLAB programs: . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9 Receiving user input from keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.10 Writing formatted output to the screen: . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.10.1 Getting help on commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.10.2 How do you learn programming? . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.10.3 Fundamental building blocks of a computer program . . . . . . . . . . . . . . . 23
1.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4
2 Performing Calculations 25
2.1 MATLAB as a Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.2 Computations in MATLAB programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.1 Variables, Identifiers and Assignments . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.3 Variable Names: Rules and Practices . . . . . . . . . . . . . . . . . . . . . . . 27
2.2.4 MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.3 Top-down program design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.4 Arithmetic and Logical Operators in MATLAB . . . . . . . . . . . . . . . . . . . . . . 32
2.5 Built-in commands/insructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.6 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.6.1 Creating vectors: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.6.2 Accessing elements of a vector: . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.6.3 Updating elements of a vector: . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.6.4 Vector operations: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.7 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.7.1 Creating matrices: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.7.2 Accessing elements of a matrix: . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.7.3 Modifying elements of a matrix: . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.7.4 Matrix operations: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.8 Cell Arrays: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

3 Functions 42
3.1 Abstraction through functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.2 Using MATLAB functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.3 Creating and Testing MATLAB functions . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.4 Important facts regarding MATLAB functions . . . . . . . . . . . . . . . . . . . . . . . 46
3.5 Features of a well designed function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
3.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

4 Selection - Branching 50
4.1 Branching with if-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.1.1 if-else syntax and flow chart representation . . . . . . . . . . . . . . . . . . . . 51

5
4.1.2 Relational Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.1.3 Branching with if-elseif-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.1.4 Nesting if-else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.1.5 Evaluating Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.2 Branching with switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

5 Repetition - Looping 63
5.1 Using a while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.2 Using a for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.3 Application of repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.4 Sampler with a for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
5.5 Sampler with a while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.6 Which type of loop do I use (for or while)? . . . . . . . . . . . . . . . . . . . . . . . 72
5.7 Flow of Control within Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.7.1 break statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.7.2 continue statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.8 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.9 Loop Related Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

6 Input-output 80
6.1 Saving MATLAB results in a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.2 Reading data form a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.3 Lower level input/output functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6.3.1 Opening files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.3.2 Closing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.3.3 Reading from a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
6.3.4 Writing to a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.3.5 Plotting data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

7 Program Design 94
7.1 Bottom-up program implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.2 Top-down design and bottom-up implementation with functions . . . . . . . . . . . . . 94

6
7.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

7
Chapter 1

Introduction

In this chapter, you will get a basic introduction to computer programming and the role of computer
programs in Engineering System Design. Following an introduction to MATLAB, you will learn how
to write simple MATLAB programs. Finally you will be introduced to the basic programming features
which will be covered in the rest of the topics.

1.1 What is a computer program

A computer program, also referred to as a computer application (or sometimes simply an app), performs
a user-defined task. We use computer programs everyday. When you access Google to do a search,
behind it is a computer program that runs (also referred to as executes in the computer terminology)
and performs the action you requested. Every application in your mobile phone is a computer program.
Organizations use computer programs for their everyday tasks; for example a bank will use a computer
program to compute the interest for each account.
A computer program is a sequence of instructions, also referred to as commands, written by a computer
programmer in a language that the computer can interpret. The language used to write a computer
program is called a programming language.
When a program executes, the computer performs the actions specified by the commands.
When you use a computer program, you are merely a user, also referred to as an end-user of the computer
program written by somebody else. In this module of the subject, you will learn how to write computer
programs to solve engineering design problems.

1.2 Role of computer programs in Engineering System Design

The obvious question now running through your mind is, “We are going to be Engineers not Computer
Programmers; why do we have to learn how to write computer programs?”. The simple answer is,
computer programs help engineers, regardless of the engineering discipline, to solve engineering design
problems. Once you learn programming you will also find that computer programming is fun!
Computer programs have many different uses in engineering system design. Following are some com-
mon examples:

8
• Understand or predict the behaviour of the system before actually building the real system; this is
called a computer simulation.

• Verify the behaviour of a physical system.

• Decide on the best (optimal) design parameters for an engineering system.

• Solve mathematical equations that do not have a closed form solution or are hard to compute
manually.

• Simplify and approximate the behaviour of a complex system or process that is hard to understand.

You will come across many more uses for computer programs during your degree and in your career
as an engineer, especially in today’s world as an engineer. You will use programs such as computer-
aided design/manufacturing (CAD/CAM)software, Simulation Program with Integrated Circuit Empha-
sis (SPICE/PSpice for circuit design, and many more to solve engineering design problems. Sometimes,
you will have to write your own computer programs to solve problems. Therefore, programming is a
basic skill every engineer should have!

1.3 Motivating examples

In this section, we will attempt to motivate the advantages of using computer programs to solve engineer-
ing problems through a few simple examples. The first two examples are based on examples you have
seen in the first module of the subject and, therefore, you should be familiar with the problems (these
may not be the best examples for the need for programming, but they have been chosen because all of
you are familiar with them).

1.3.1 Example 1: Chemical Process Alarm Generator

Consider for example, the Chemical Process Alarm Generator, shown in Figure 1.1; you briefly looked
at this system in the first module of the subject.

Figure 1.1: Block diagram of a Chemical Process Alarm Generator.

9
This system must generate an alarm if the temperature, VT , or the pressure, VP , exceeds the respective
thresholds VT R and VP R . This is a relatively simple system to design and implement using simple logic
gates and it easy to determine the output given an input temperature and pressure. This problem is said
to have a closed-form solution; it has an exact mathematical solution.
Problem Statement:

In a real system, temperature and pressure measurements are performed by devices which have a margin
of measurement error. Given the probability distributions of the measurement errors for the temperature
and pressure transducers, how would you select VT R and VP R such the probability of false positives (an
alarm is generated when there should be no alarm) is less than 0.01?
Although you might be able to solve this through a mathematical formulation, it is easier to solve this
through writing a computer program that mimics the behaviour of the system, called computer simu-
lation. Some problems do not have exact mathematical solutions, and can be solved using numerical
methods. For such problems, computer simulations are useful.

1.3.2 Example 2: Analog-to-Digital Converter

Figure 1.2 shows the block diagram of an Analog-to-Digital (A/D) Converter you studied in the first
module of this subject. An A/D converter converts an analog signal to a digital signal.

Figure 1.2: Block diagram of an Analog to Digital Converter.

Consider an engineer who wants to find the answers to the following two questions.
Problem Statement:

1. Given an audio signal that is sampled at a rate of fs samples per second and quantized to N
quantization levels, how much memory is required to store a song which is t seconds in duration
if binary coding was used?
This problem is straightforward to solve through a mathematical formula, because there is a spe-
cific closed form solution. Also, the answer does not depend on what the audio signal is, because
we are only interested in the number of bits.

10
2. An engineer has built an A/D converter and wants to verify if it is behaving as expected. i.e., for
a given input signal, sampling rate and number of quantization levels, is the digital signal output
from the A/D converter accurate?
Although possible, manually computing the output digital signal would be a tedious task. Because
the output will depend on the input signal, manual computation will have to be repeated for every
input signal. Such a problem is easier to solve through a computer simulation.

1.3.3 Example 3: Parachute design problem.

Consider the following engineering design problem faced by a Mechanical Engineer.


Problem Statement: An engineer is required to design a parachute which attains a particular velocity
when it touches the ground.
The velocity v(t) at time t, of a falling parachute is given by the following analytical equation:
gm c
v(t) = (1 − exp− m t )
c
where g - gravitational constant, m - mass and c - the drag coefficient which depends on the design of
the parachute.
If you were required to find the drag coefficient c, to attain a particular velocity v(t), at a particular time
t, for a given mass m, you would be require to solve this equation to find c, and there is no straight
forward solution for this.

1.4 Why computer programs?

Computer programs can solve numerical problems more efficiently than humans because of two main
reasons.

• Computers can do repetitive tasks at higher speeds than humans and, therefore, such tasks are more
efficient when performed by a computer than when they are done manually; computers do not get
bored or tired.
• Computers allow us to automate computational tasks. Through writing computer programs you
can automate tasks hence they can be done without the need for human intervention (for the most
part). This means that the tasks can be done anytime, more efficiently, and without human error.

Note: The computer program are written by humans. Therefore, if the program is not correct, obviously
the task performed will not be correct. Therefore, the intelligence of the computer is more or less limited
by what it is programmed to do.
Computer programs have many uses beyond engineering system design; following are some of them:

• general purpose computer applications


• as large scale software systems - Google, Facebook etc
• medical, e-Commerce applications
• many more

11
1.5 Computer Software, Hardware & Operating System

1.5.1 Software:

Computer programs are referred to as the software. In this module you will be learning how to write
software.

1.5.2 Hardware:

The device on which the computer program runs or executes is called the hardware. Computer programs
can run on computers or on computational devices. For example, smart phones can run computer pro-
grams. Basic hardware for a computer consists of three main components: a Central Processing Unit
(CPU); Storage; and input-output devices.

Central Processing Unit (CPU):

CPU is the “brain” of the computer. It is responsible for performing the instructions of a computer
program (software) by doing computations, input-output, etc.

Storage:

Computers use two main types of storage mediums: memory and disk. Information that is stored tem-
porarily while doing computational tasks is held in memory. Information that needs to be persisted for
the longer term, such as the programs you write and the data the programs generate, is normally stored
in the disk; they are stored in computer files. A computer file, more often simply referred to as a file in
computing, is a container for storing information (data) on the computer disk. A disk can hold multiple
files, each identified using a unique name. Files are often classified based on the type of information they
contain, and it is common to use an extension to identify the type of file.
You have already seen files, and have used them. Most of you would have written documents, which
were saved in files with an extension of .doc or .docx which indicates that they are Microsoft Word
documents. File extensions that identify the type of file is not always required, but it is a good practice
to use them.
You will be using files to store your programs and data generated from programs.
Files are stored in directories and directory structures are hierarchical.

Input-output Devices:

Computers communicate with the out-side world via input-output devices. The two most common input
devices you are familiar with are the keyboard and the mouse. The most common output device is the
monitor or the screen that display the information to you.

12
1.5.3 Operating System:

Computational devices also come with pre-installed system software that help run programs we write.
This software is called the operating system or the platform. For example, Microsoft Windows, Unix,
Linux, MAC-OS, iOS, Android are operation systems.
Software will interact with the outside world through input-output devices, with the support provided
by the Operating System.

1.6 Programming languages

Computer programs are written in a language the computer can understand; such a language is referred to
as a programming language. Many programming languages exist today. Some examples are: Basic, C,
C++, C#, Java, Python, Fortran, Pascal, Algol, Haskell, Prolog, Lisp, Smalltalk, Assembly, MATLAB.
Each programming language has its own characteristics. Programming languages can be broadly classi-
fied into the following categories.

• High-level vs low-level: High-level languages are easy to program (programmer’s job is easy)
whereas low-level languages require more work by the programmer. Low-level langues are closer
to the machine than the human.

• Procedural, Object-oriented, Functional, Logic-based, Multi-paradigm: This classification is


largely based on how you break down the problem when designing the program.

• Interpreted vs Compiled: This classification is based on how the computer runs the program.
Interpreted languages are run by the computer an instruction at a time (without any translation up-
front), whereas complied languages translate the program to a machine specific set of instructions
before it is run. Therefore, compiled languages normally run faster than interpreted languages.

• Platform dependent vs platform independent: A platform independent language once written


can run on any operating system without modifications to the program.

Do not worry about the classification at this time. You will understand it when you have more exposure
to programming.

1.7 Introduction to MATLAB

In this module of the subject you will learn general computing concepts and develop computational
thinking skills that will be useful when learning any programming language. However, we will use
MATLAB as our programming language.
MATLAB is more than just a programming language. It is a powerful modelling and simulation platform
widely used by engineers and scientists. MATLAB supports a programming environment and a high level
language. MATLAB:

• is easy to learn and has less complexity in terms of programming;

• has built in capabilities to make programming and computational tasks relatively easy;

13
• it supports powerful visualization capabilities; and

• is enhanced by a large number of toolboxes that give additional computational capabilities e.g.
statistical toolbox, image processing toolbox and many more.

MATLAB is a High-level, Multi-paradigm, Interpreted, Platform independent language, widely


used by Engineers.

1.8 Programming with MATLAB

A MATLAB program consists of a sequence of instructions, also referred to as commands; in fact, this is
true for any program regardless of the language. When a program runs, it performs the actions specified
in this instruction.

1.8.1 MATLAB instructions/commands

We will first try to understand a basic MATLAB instruction. The following MATLAB instruction will
display a message on the screen.
disp(’Hello world!’);
We will now take a closer look at this instruction.
This instruction has two components. The command and input arguments.

Command:
In this example, disp is a command that tells the computer to display something on the console
(screen or monitor). At this point, for simplicity, we refer to disp as a command but as we
progress through the lectures will understand what disp really is!

Input Arguments:
Input arguments are provided within parenthesis (brackets); sometimes they are referred to as
parameters although this is not quite the right term. For the disp command, the input argument
is what you want to display on the console; in this case, the string, Hello world!. The single
quote around the phrase Hello world! indicates that it is a string; you will learn more about
this later.
This particular command has only one input argument, but commands can have more than one
input argument as you will soon see. If there is more than one input argument, they are separated
by commas within the parenthesis.

The semicolon at the end indicates the end of command. This is optional. You will see the effect of the
semicolon when you write programs.

The next step is to run or execute this command. MATLAB instructions can be in the interactive mode.

14
1.8.2 MATLAB interactive mode

You will need a computer in which MATLAB is installed. Assuming you are at a computer where MAT-
LAB is installed, start MATLAB by double clicking on the MATLAB icon on your computer and you
will see the MATLAB user interface shown in Figure 1.3 (Depending on what you have done previously,
and how MATLAB is configured you might see a different window).

Command Window

Figure 1.3: MATLAB User Interface.

To run the instruction, in the command window, at the prompt (>>, enter the disp command as follows
and observe the output.

>> disp({’Hello world!’}); <- what you type


Hello world! <- program output

If you saw the above, you just executed a MATLAB instruction successfully!
As stated earlier, a program is a sequence of instructions. You can type in instructions, one or more at
a time, on the command window to perform the task you want, However, these instructions will not be
available to you if you exit MATLAB and restart.
A program is a sequence of instructions that can be executed whenever you want to, and therefore,
programs are written and saved. We will next look at how to write a MATLAB program, also referred to
as a MATLAB script.

1.8.3 First Program: Display a message on the screen

The first program you learn to write when learning a programming language is the “Hello world” (we
will refer to it as HelloWorld for short) program. This program prints the message “Hello world!” on the
screen, referred to as the console. As you can guess, the instruction we used before can be used in this
program.
Problem Statement: Write a MATLAB program that displays the String Hello world! on the
screen.

15
The HelloWorld program in MATLAB is shown in Listing 1.1.

Listing 1.1: HelloWorld.m


1 % HelloWorld.m
2 % This program writes a message to the console
3 % Version 1.0 27/02/2014
4 % Author Shanika Karunasekera karus@unimelb.edu.au
5

6 % Display a message on the console


7 disp(’Hello world!’);

Explanation:
The program has seven lines (line 5 in empty, and does not have a purpose other than making the program
more visually appealing and easy to read). The rest of the lines are of two different categories: Comments
and Instructions.

• Lines 1-4 and 6: These are comments.

– A line starting with % is a comment in MATLAB.


– Comments are ignored by the computer; they are for the benefit of the human readers of the
program
– Commenting code for future readability and understandability is strongly recommended
– Develop this habit from the beginning
– Include the author, version, date and a high level introduction at the top

Note: The examples shown in these course notes (and lecture slides) will have minimal comment-
ing to fit the slide space; do not use these programs as examples of good commenting. When you
write programs, you are expected to write comments to explain your program.
In your assignments you will be assessed on good commenting.

• Line 7: This is an instruction. As we explained before this instruction displays the message
Hello World! on the screen.

When writing computer programs, strictly following the rules of the language, called the SYNTAX of
the language, is important. If you do not, the programs will either fail or in some cases do what was
not intended.

1.8.4 Running MATLAB programs:

Now that you understand the first program the next step is to run the program to perform what is expected.
Follow the steps below:

1. Start MATLAB by clicking on the icon.

2. Use MATLAB editor to write the program by following the steps below:

16
Editor

Figure 1.4: MATLAB User Interface.

(a) Choose File→New→Script and the MATLAB editor, as shown in Figure 1.4 will open
(b) Type in the program lines in the editor.
(c) Choose File→Save As, and change to the directory where you want to save the file.
(d) Enter the name of the file as HelloWorld and save - the program will be saved in a file
named HellowWorld.m which is a MATLAB script file. You may choose any name for the
file but always use a meaningful name.

3. Run the program:

(a) Click on the green arrow on the top menu to run the program (if you saved your program in
a different directory from where you currently were, MATLAB will ask you if you want to
change the directory; respond ’yes’ to this question).
(b) Observe the output on the command window.
(c) You can also run the program by typing HelloWorld at the command line prompt if you
are in the directory where you saved the file.

This sequence of actions created a file named HelloWorld.m, which was saved in the current working
directory. Notes:

• A MATLAB program is stored in a script file (HelloWorld.m).

• MATLAB script files have a .m file extension.

• When you run the program, MATLAB interprets the commands and performs the necessary actions
to complete the task based on the commands.

Program Output:
>> HelloWorld
Hello world!

17
1.9 Receiving user input from keyboard

The first program, HelloWorld.m, demonstrated how the disp() command in MATLAB could be
used to display a string on the screen. This is referred to as console output. This program is fairly
limited in its functionality. It only displays the particular string (in this case Hello world!) it was
programmed to display. If a different string was required, the programmer has to explicitly change the
program and, therefore, this program is not very useful for a user who is not a programmer.
Programs must be able to accept information from users. For example, Google accepts the words you
provide for its search (user input); you input this information through the keyboard. Without this capa-
bility Google would be not useful!
We will now learn how a program can accept user input from the keyboard using the input command;
this is referred to as console input.
Problem Statement: Write a program that prompts the user to input a number and displays this number
on the screen.
Program Listing:
Listing 1.2 is a program for this problem.

Listing 1.2: InputDisplay.m


1 % InputDisplay.m
2 % This program demonstrates how a program can accept user input
3 % from the keyboard
4 % Version 1.1 30/03/2015
5 % Author Shanika Karunasekera karus@unimelb.edu.au
6

7 % Prompt user for a number


8 a = input(’Enter a number: ’);
9

10 % Display a message on the console


11 disp(a);

Explanation:
Let us take a close look at this program. This has two non-comment lines which we will explain below.

• Line 8: The input command is used for accepting user input from the keyboard.
– This command has one input argument; the string, Enter a number: which gets dis-
played on the screen when the command executes, similar to the disp command.
– This command also has an output argument, a.
– When this command executes, the program displays the message Enter a number:, and
waits for user input from the keyboard.
– The value the user enters, is stored in a (in the computer memory). For now we have not
given a full explanation of what a really is; we will defer a full explanation of this to the next
topic.
• Line 11: This is the same command as you saw in your first program. However, in this case
the input argument does not have the single quote around it, as was the case in Hello world!

18
string. When there is no quotes around the input argument, this implies that the value stored in the
argument will be printed rather than the particular string (in this case the value you entered rather
than the string ’a’);

Program Output:

>> InputDisplay
Enter a number: 3
3

>> InputDisplay
Enter a number: 3.5
3.5000

Note: Notice that the value was displayed, formatted to four decimal places and in this case we did not
have an option to choose the format (for example to display it rounded to two decimal places). You will
learn how to do more customized formatting later in this chapter.
Now consider what happens if you input a character string, rather than a number, in this case.

>> InputDisplay
Enter a number: hello
Error using input
Undefined function or variable ’hello’.

Error in InputDisplay (line 8)


a = input(’Enter a number: ’);

Enter a number:

You can see that the program did not display your input as expected. This is because the syntax you used
for this input command could only accept numbers, but not characters.
In the next program you will see how to use the same command to accepts numbers as well as character
strings.
Problem Statement: Write a program that prompts the user to input a string and displays this string of
the screen.
In this case, we will enhance the previous program to accept numbers as well as strings as inputs. You
program must be able to display numbers as well as alphabetic character strings.

19
Program Listing:
Listing 1.3 is a program for this problem. Because we are modifying the existing program we have
changed the version number to 1.2, keeping the same name for the program.

Listing 1.3: InputDisplay.m


1 % InputDisplay.m
2 % This program demonstrates how a program can accept user input
3 % from the keyboard
4 % Version 1.2 30/03/2015
5 % Author Shanika Karunasekera karus@unimelb.edu.au
6

7 % Prompt user for a charater string


8 a = input(’Enter a character string: ’, ’s’);
9

10 % Display a message on the console


11 disp(a);

Explanation:
Let us take a closer look at this program. This has two non-comment lines which we will explain below.

• Line 8: The input command is used as in the previous example, but in this case, the command
has two input arguments: the first is the string that will be displayed when the command executes,
as before. The second argument, ’s’ instructs the computer to accept any character string (not
just a number).

• Line 11: This is the same as in the previous program.

Program Output:

>> InputDisplay
Enter a character string: hello
hello
>> InputDisplay
Enter a character string: 3
3
>> InputDisplay
Enter a character string: 3.5
3.5

As you will notice, this program can accept both alphabetic and number strings, because numbers are
also characters. You will also see that 3.5 in this case was not formatted to four decimal places.

1.10 Writing formatted output to the screen:

In the previous examples you saw the simplest form of output command in MATLAB, the disp com-
mand. Although this command can be used to display simple output, it is limited in the formatting you

20
can have for the output. Sometimes it is necessary to display strings in customized formats, for which
we can use MATLAB fprintf command, which we will now look at.
Problem Statement: Write a program that prompts the user to input a number followed by a character
string and displays them on the screen.
Program Listing:
MATLAB fprintf command allows you to print formatted output, as shown in Listing 1.4.

Listing 1.4: FormattedOutput.m


1 % FormattedOutput.m
2 % This program demonstrates how to display formatted output
3 % on the screen
4 % Version 1.1 30/03/2015
5 % Author Shanika Karunasekera karus@unimelb.edu.au
6
7 % Prompt user for a number
8 a = input(’Enter a number: ’);
9 % Prompt user for a string
10 b = input(’Enter a character string: ’, ’s’);
11

12 % Display formatted output on the screen


13 fprintf(’The number you entered is: %d \n’, a);
14 fprintf(’The string you entered is: %s \n’, b);

Explanation:

• Lines 8 and 10: You have already seen these commands in your previous programs. In this case,
because we are using both commands in the same program, we have to use two different names, a
and b, to store the values.

• Lines 13 and 14: Let us take a closer look at the fprintf commands on lines 13 and 14. Both
these commands have two input arguments.
The first argument is a string, similar to what you have seen in the disp and input commands.
However, these strings are a bit different from the strings that were used in the previous commands;
they have two special features/charaters, which imply a particular runtime behaviour, which re-
quires a further explanation:

– The characters preceded by % (%d and %s) are format strings, which have a special
behavior when the command executes. When the command executes, the value stored in the
second argument (a and b in this case), gets substituted in place of the format string. Observe
the output of the program and you will understand this better. The letters in the format string
indicate the type of value substituted. Following are some of the possible types of data:
%d - integer
%f - float (a number with decimal points)
%c - character
%s - string

21
– The second special character in these strings is the \n character at the end of the string.
The character n preceded by the \, referred to as an escape character, makes this pair of
characters a non-printable character. Although such character pairs do not get printed on
the screen, they have a special meaning; in this case \n, implies a new line (or line feed).
Because the n appeared at the end of the string, the cursor will be placed on a new line after
printing the string and anything that is output on to the console will appear on a new line.
Note: Try running the program without the \n and observe the output of the program and
you will understand the role of the control character better. Then place the \n somewhere in
the middle of the string and observer the output.
Following are some common escape characters:

\b - Backspace
\f - Form feed
\n - New line
\t - Horizontal tab

Program Output:

>> FormattedOutput
Enter a number: 3
Enter a character string: hello
The number you entered is: 3
The string you entered is: hello

fprintf command has powerful formatting capabilities which you can discover by experimenting.
Follow are some examples.

• In the above example, you could have printed both values with a single fprintf command as in
the following example.

>> fprintf(’The number is: %d and the string is: %s \n’, a, b);
The number is: 3 and the string is: hello

In this case, as you will notice, the fprintf command has three input arguments. The latter
two input argument values are substituted for the two format strings in the first argument when
the program runs, in the order they appear in the string. There is no limit to the number of format
strings that can appear in the first string, and therefore, there is no limit to the number of input
arguments to the command (we need a value for each format string).

• Now look at the following variation of the same command (%d is replaced by %4d).

>> fprintf(’The number is: %4d and the string is: %s \n’, a, b);
The number is: 3 and the string is: hello

In this, %4d implied that you need to at least have 4 spaces reserved for the number. It left 3 spaces
in front because the number is a single digit number

• Let us suppose c was a floating point number (as opposed to an integer) equal to 4.2365. Observe
the following commands and the corresponding outputs to understand how formatting works.

22
>> c = 4.2365
>> fprintf(’The floating point number is equal to %f\n’, c);
The floating point number is equal to 4.236500

>> fprintf(’The floating point number is equal to %0.2f\n’, c);


The floating point number is equal to 4.24

>> fprintf(’The floating point number is equal to %6.2f\n’, c);


The floating point number is equal to 4.24

If you run a few variations of the above command on the MATLAB interpreter, you should be able
to understand the behaviour of the different format strings and their variations.

1.10.1 Getting help on commands

MATLAB has a large number of commands and you will not know all of them, and you are not expected
to remember all of them. If you need to know more about a command, its behaviour and input/output
arguments, MATLAB help command is what you need.
For example, if you type the following command,

>> help fpritnf

at MATLAB command prompt, you can find all about the fprintf command.
If you did not know the name of the command, just type help to get a categorized list of commands.
Also the doc command gives more details about each command.

1.10.2 How do you learn programming?

The only way you can learn programming is by doing it yourself. You cannot learn programming just by
reading a book, or watching others program. Therefore, start writing programs today. Start running the
example programs yourself, and try to understand what happens when the program runs. Try changing
the programs to observe the behavior. Do not be afraid to make mistakes; you will learn a lot from your
mistakes.
As students, you will have access license to install MATLAB on your personal computers to be used for
educational purposes. The instructions on how to install will be available via LMS.

1.10.3 Fundamental building blocks of a computer program

You have now learnt a simple but fundamental capability of a computer program.
Input-output: the ability to accept input from the keyboard and displaying output on the console (you
will learn more on input-output later).
Writing more advanced and useful programs requires you to learn a few more fundamental programming
capabilities [1], which are put together to perform more complex programming tasks. In the follow-
ing topics, you will learn four additional fundamental capabilities that will help you write more useful
computer programs:

23
• Calculation: Doing computational tasks

• Functions (Abstraction): Creating self-contained modules that can then be put together to create a
program

• Selection (Making choices): Branching

• Repetition (Iteration): Looping

1.11 Summary

In this topic you got a basic introduction to programming and the role of programming in engineering
system design. We looked at MATLAB as a general purpose computing environment which supports a
programming environment as well as a programming language. You learnt how to write simple MAT-
LAB programs (scripts) that interacted with the user, through getting user input from the keyboard and
displaying output on the screen. You learnt how to display basic output as well as formatted output.

24
Chapter 2

Performing Calculations

In the first topic, you learnt a fundamental capability in programming: console input-output; how to
accept data from the keyboard and output the data to the screen.
In this topic, you will learn another fundamental programming capability, the ability to perform com-
putational tasks or calculations. We will first look at how to do computations in MATLAB. MATLAB
can be considered as a powerful calculator. We will briefly look at some computational capabilities in
MATLAB through the interactive mode, and then we will learn how to write simple computer programs
that perform computations (calculations), using the top-down design approach.

2.1 MATLAB as a Calculator

MATLAB can be used as a powerful calculator to perform mathematical computations. MATLAB sup-
ports basic arithmetic operations, such as addition, subtraction, multiplication and division, as well as
more advanced mathematical functions such as log, exp, sin, cos etc.
The following examples will demonstrate some of the calculation capabilities in MATLAB through the
interactive mode.
Basic arithmetic:

>> 5.6 + 3.4


ans =
9
>> 2.3 * 7
ans =
16.1000

Other mathematical operators:


>> mod(23,3)
ans =
2
>> exp(5)
ans =
148.4132

25
2.2 Computations in MATLAB programs

Computer programs are useful to perform tasks that require complex computations. Such complex com-
putations often require multiple computational steps, with values computed in one command used in later
commands. You have already seen this in even the simple programs we learnt in the previous topic. We
will now look at this more formally.

2.2.1 Variables, Identifiers and Assignments

In computer programs, values computed in one step are often required to be stored in the computer
memory and retrieved for later use.
Such computed values in a program are called variables.
Variables are given names, known as identifiers, to identify them uniquely.
Values are assigned to variables using the = operator.
In fact, you have already seen variables in the first topic, when we used the input command. Consider
the following command:

a = input(’Enter a number:’)

In the above statement, the output argument of the input command, is assigned to a variable with
identifier, a.
In this case, a was a variable that stored the value, although we did not formally introduce them as
variables at the time.

2.2.2 Expressions

Equations used to perform basic computations are called expressions.


Results of expressions can also be assigned to variables.
Let us take a look at some examples.
Example: A variable with identifier width is assigned a value of 5.

% A variable with identifier width is assigned a value of 5


>> width = 5
width =
5

Example: A variable with identifier length is assigned the value from the expression width + 5.
% A variable with identifier length is assigned the value
% from the expression width + 5;
>> length = width + 5
length =
10
Example: A variable with identifier length is assigned a value of 20.

26
% A variable with identifier length is assigned a value of 20
% Now the value of length will be set to 20 and the previous
% value 10 will be forgotten
>> length = 20
length =
20
Example: Increment the value of a variable x by 1.
% Increment the value of a variable x by 1.
>> x = 3;
>> x = x + 1
x =
4
The last example, is an important type of assignment which you will often come across in the future
topics and, therefore, it is necessary to understand the behavior of this operation - basically incrementing
the value of a variable by a specified amount.
When assigning a value to a variable, the expression on the right-hand side is first computed and the
result is assigned to the variable on the left hand side. The expression must always appear on the right
hand side.
Unlike in some other programming languages, MATLAB variables do not have to be pre-declared with
a type. Variable type is determined by the value assigned to it.

2.2.3 Variable Names: Rules and Practices

MATLAB variable names (identifiers):

• Must start with a letter


• Can be followed by letters, digits or underscores
• Names are case sensitive (X and x are not the same)
• namelengthmax command returns the maximum allowable length for a variable name.
• MATLAB keywords cannot be used as variable names e.g. if, while, else, end are
MATLAB keywords (as you will learn later) and cannot be used as variable names
• iskeyword command returns a list of MATLAB keywords

Note: Always use meaningful names for identifiers. This improves the understandability of your pro-
grams. For example, if you are using a variable to store the value of weight of a particular item, using
a variable with identifier weight will make your program easier to understand than using an arbitrary
variable name, such as x.

2.2.4 MATLAB Workspace

MATLAB workspace contains the variables you create during a session; who and workspace commands
display the variables available in the workspace.

27
>> who
Your variables are:
length width

>> workspace

2.3 Top-down program design

Before you write a computer program to solve a problem, you must first understand the problem to be
solved and then design a solution for it. An algorithm is a sequence of steps that are required to perform
a particular task or solve a problem.
A common and effective approach to designing a computer program is the top-down design approach [2].
In the top-down design approach:

Step 1: Break the solution down to smaller steps that are manageable - algorithm

Step 2: Refine each step until all the steps are small enough to manage

Step 3: Implement the refined steps (written as MATLAB code) and test each step

Step 4: Combine the steps and test the solution as a whole - we will learn how to do this for complex
applications using the bottom-up implementation strategy in the next topic.

Let us now try to understand the top-down approach to design through some simple examples.
Problem Statement: Write a MATLAB program that accepts the temperature in Fahrenheit as input
from the keyboard and then displays the temperate in Celsius on the screen.

Step 1: Break the solution down to smaller steps that are manageable - algorithm
Pictorial representations (schematic diagrams) that make is easier to visualize the problem domain
is often useful for breaking down the problem to steps. There are many different types of such
diagrams/models, and in this example we will use a commonly used diagram, a Flowchart.
Figure 2.1 is a flowchart which represents the steps involved.

Step 2: Refine each step until all the steps are small enough to manage
In this case, each step is small enough and does not need further refinement. Therefore we will
identify the input/output for each step and will not break it down further.

1. Get user input:


• the temperature in Fahrenheit
2. Calculate the result:
• identify the required formula
• convert Fahrenheit to Celsius
3. Display the output
• the temperature in Fahrenheit

28
Figure 2.1: Flowchart for Fahrenheit To Celsius Conversion Problem

• the temperature in Celsius

Step 3: The refined steps are implemented (written as MATLAB code) and tested
Program Listing:
Listing 2.1 shows MATLAB code for the problem.

Listing 2.1: FahrenheitToCelsius.m


1 % FahrenheitToCelsius.m
2 % This program converts degrees Fahrenheit to degrees Celsius
3 % Input: degrees Fahrenheit
4 % Output: degrees Celsius
5

6 % Prompt user for input


7 temp_fahr = input(’Enter temperature in degrees Fahrenheit ’);
8
9 % Convert temperature to degrees Celsius
10 temp_celsius = (temp_fahr - 32)*5/9;
11
12 % Display output
13 fprintf(’Fahrenheit %f\n’, temp_fahr);
14 fprintf(’Celsius %f\n’, temp_celsius);

Explanation:
The program should be self explanatory.

• Line 7: Accept user input.


• Line 10: Convert the temperature from Fahrenheit to Celsius using the appropriate formula.
• Lines 13 and 14: Display output.

Program Output:

>> FahrenheitToCelsius

29
Enter temperature in degrees Fahrenheit 212
Fahrenheit 212.000000
Celsius 100.000000

>> FahrenheitToCelsius
Enter temperature in degrees Fahrenheit 32
Fahrenheit 32.000000
Celsius 0.000000

Enter temperature in degrees Fahrenheit 100


Fahrenheit 100.000000
Celsius 37.777778

Step 4: The solution is tested as a whole


To test your program you will need to give different input values for the temperature in Fahrenheit,
and verify the output you get is correct by comparing it with the values you get for the same when
computed manually or using a calculator.
Note: It is important to test your program with different input values and check it with the expected
values.

Problem Statement: Write a MATLAB program that accepts the radius and height of a cylinder as
inputs from the keyboard, computes the surface area of the cylinder, and displays it on the screen.

Step 1: Break the solution down to smaller steps that are manageable - algorithm

Identify the steps involved and write it in the form of a flowchart (Figure 2.2):

Figure 2.2: Flowchart for computing the surface area of a cylinder

Step 2: Refine each step until all the steps are small enough to manage
In this case, each step is small enough and does not need further refinement. Therefore we will
identify the input/output for each step and will not break it down further.

1. Get user input:


• the radius and height

30
2. Calculate the result:
• identify the required formula
• compute the area using the formula
3. Display the output
• the Radius, height and area

Step 3: The refined steps are implemented (written as MATLAB code) and tested
Listing 2.2) shows the program listing.
Program Listing:

Listing 2.2: CylinderSurfaceArea.m


1 % CylinderSurfaceArea.m
2 % This program computes the surface area of a cylinder
3 % Input: radius, height
4 % Output: surface area
5

6 % Prompt user for input


7 radius = input(’Enter radius(meters) ’);
8 height = input(’Enter height(meters) ’);
9
10 % Compute surface area
11 surf_area = 2*pi*radiusˆ2 + 2*pi*radius*height;
12
13 % Display a message on the console
14 fprintf(’Surface area = %f square meters\n’, surf_area);

Explanation:
This program does not need further explanation because by now you would understand all the
steps except for pi, in Line 11, which is a constant defined in MATLAB which you can use in
your programs.
Program Output:

>> CylinderSurfaceArea
Enter radius(meters) 3.2
Enter height(meters) 4.1
Surface area = 146.775209 square meters

Step 4: The solution is tested as a whole


To test your program you will need to give different input values and verify the output you get is
correct by comparing it with the values you get for the same when computed manually or using a
calculator.

For simplicity, both the above examples only looked at programs that only required one level of break-
down. In the next topic, we will look at more complex examples that require multiple levels of program
breakdown.

31
2.4 Arithmetic and Logical Operators in MATLAB

For performing computations MATLAB supports a range of arithmetic and logical operators.
Table 2.1 shows some of the arithmetic operators supported by MATLAB.

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
ˆ Power

Table 2.1: Arithmetic Operators in MATLAB

Table 2.2 shows some of the logical operators supported by MATLAB.

Operator Operation
& AND
&& Short circuit AND
| OR
|| Short circuit OR
xor(,) XOR
˜ NOT

Table 2.2: Logical Operators in MATLAB

Previously we looked at example programs that use MATLAB arithmetic operators. Let us now try to
understand how to use logical operators in MATLAB through a simple example.
Problem Statement: Write a MATLAB program that accepts inputs A, B and C from the keyboard and
computes the output of the logic circuit shown in Figure 2.3.

Figure 2.3: Logic Circuit.

32
Program Listings:
Listings 2.3 and 2.4 show two possible solutions.

Listing 2.3: Circuit1 1.m


1 % Circuit1_1.m
2 % Prompt user for input
3 A = input(’Enter A ’);
4 B = input(’Enter B ’);
5 C = input(’Enter C ’);
6
7 % Compute output
8 Z = (A|B)&˜C;
9
10 % Display output
11 fprintf(’Z = %d\n’, Z);

Listing 2.4: Circuit1 2.m


1 % Circuit1_2.m
2 % Prompt user for input
3 A = input(’Enter A ’);
4 B = input(’Enter B ’);
5 C = input(’Enter C ’);
6

7 % Compute output
8 Z = (A||B)&&˜C;
9

10 % Display output
11 fprintf(’Z = %d\n’, Z);

Explanation:
The only difference between the programs is, Listings 2.4 uses the short circuit OR and AND operators.
Short circuit operators (&& and ||) do not evaluate the second expression or variable if it is not needed.
For example, in Z = (A||B)&& C: If A||B is 0, then the rest of the expression is not evaluated, and Z
is immediately assigned 0. The second program is therefore more efficient than the first program.

2.5 Built-in commands/insructions

MATLAB supports additional mathematical operations such as sin, cos, log through built-in com-
mands.
The syntax for using a built-in command is as follows:

[y1, y2, y3 ....] = command_name(x1, x2, x3....)

For example,
> x = 3;

33
> y = log(x)
y
1.0986
log command takes one input argument, variable x in this case, and returns one output argument,
variable y in this case, the natural logarithm of the input value.
In fact, you have already used built-in commands for non-mathematical operations.
input(), disp(), fprintf() are MATLAB built-in commands.

Operator Operation
exp Exponential
log Natural Logarithm
log10 Base 10 Logarithm
log2 Base 2 Logarithm
pow2 Base 2 Power
sqrt Square Root
log10 Base 10 Logarithm
nthroot Real n-th root of real numbers

Table 2.3: Built-in commands in MATLAB

Operator Operation
fix Round towards zero
floor Round towards minus infinity
ceil Round towards plus infinity
round Round towards nearest integer
mod Modulus signed remainder after division
sqrt Square Root
rem Remainder after division

Table 2.4: More Built-in commands in MATLAB

You can find out more about commands, their inputs and output through the help command in MATLAB.
For example to get help about the log command, you could do the following:

>> help log


log Natural logarithm.
log(X) is the natural logarithm of the elements of X.
Complex results are produced if X is not positive.

See also log1p, log2, log10, exp, logm, reallog.

Overloaded methods:
gf/log
codistributed/log
fints/log

34
Reference page in Help browser
doc log

Note: Although we refer to these as commands/instructions at this time, as we will explain in the next
topic, these are actually MATLAB functions; you will also be able to write your own functions.

2.6 Vectors

So far we have looked at variables which store a single value. In programs, it is sometimes useful to refer
to a collection of values by a single name.
A vector is a group of values referred to by a single identifier (name).
Each value, referred to as an element of the vector, is accessed by an index based on the position.
Let us understand how to create, access/modify elements, and do mathematical operations on vectors
through some examples.

2.6.1 Creating vectors:

Example: Create a row vector, with identifier my_vector with 4 elements, with values 2, 3, 5 and 6 (a
row vector has its elements arranged in a row)

>> my_vector = [2 3 5 6] % defines a 1 x 4 vector


my_vector =
2 3 5 6

The values of the vector get printed on the screen because the creation statement is not followed by a
semicolon. If you enter,
>> my_vector = [2 3 5 6]; % defines a 1 x 4 vector
my_vector would get created, but the values will not be displayed on the screen.
This is true for all MATLAB assignments. If the statement is not terminated with a semicolon, the
result of the most recent expression will get displayed on the screen.
Example: Find the size of my_vector

>> size(my_vector)
ans =
1 4

This indicates that my_vector has 1 row and 4 columns.


Example: Find the length of my_vector

>> length(my_vector)
ans =
4

This indicates that my_vector has 4 elements.

35
Example: Create a column vector, with identifier my_col_vector with 3 elements, with values 2, 5,
and 9 (a column vector has its elements arranged in a column)

>> my_col_vector = [2; 5; 9;] % defines a 3 x 1 vector


my_col_vector =

2
5
9

Example: Find the size of my_col_vector

>> size(my_col_vector)
ans =
3 1

This indicates that my_col_vector has 3 row and 1 column.


Vectors can be initialized as a sequence.
Example: Create a vector one_to_ten that contains values 1, 2, .....10.

>> one_to_ten = [1:10]


one_to_ten =
1 2 3 4 5 6 7 8 9 10

Example: Create a vector two_to_ten_step_2 that contains values 2, 4, 6, 8, 10.

>> two_to_ten_step_2 = [2:2:10]


two_to_ten_step_2 =
2 4 6 8 10

Example: Create a vector of length 10 with all zeros.


>> x = zeros(1,10)
x =
0 0 0 0 0 0 0 0 0 0
Example: Create a vector of length 10 with all ones.
>> x = ones(1,10)
x =
1 1 1 1 1 1 1 1 1 1
Example: Create a vector of length 10 with random integers between 1 and 10.
>> x = randi(20, 1, 10)
x =
2 5 19 4 17 11 20 2 9 3

2.6.2 Accessing elements of a vector:

Elements (individual values in a vector) are accessed using an index, that indicates the position of the
element. The valid values for the index are 1 through to the length of the vector.

36
Note: In some programming languages, such as C, the index starts at 0, but in MATLAB index starts
with 1.
Example: Assign variable x, the value of the first element of my_vector.

>> x = my_vector(1)
x =
2

Example: Assign variable y, the value of the third element of my_vector.

>> y = my_vector(3)
y =
5

Example: Try to access an element with a index greater than the length of the vector - in this case index
6 ( my_vector only contains 4 columns).

>> z = my_vector(6)
Attempted to access my_vector(6); index out of bounds because
numel(my_vector)=4.

You can also access subsets of the elements of the vector to create other vectors as seen in the following
examples.
Example: Create a vector, my_vector_1, that contains the first 3 elements of my_vector.

>> my_vector_1 = my_vector(1:3)


my_vector_1 =
2 3 5

Example: Create a vector one_to_ten_step_2 that contains the every other element of vector
one_to_ten starting from the first element.

>> one_to_ten_step_2 = one_to_ten(1:2:10)


one_to_ten_step_2 =
1 3 5 7 9

2.6.3 Updating elements of a vector:

Individual elements of a vector can be modified by assigning values to them directly.


Example: Change the value of the 4th element of my_vector to 9.

>> my_vector(4) = 9
my_vector =
2 3 5 9

Notice that only the value of the 4th element has changed.

37
2.6.4 Vector operations:

Most of the mathematical operations that are applicable to other variables are also applicable to vec-
tors. For example, simple operations such as addition and subtraction are straight forward. However,
operations such as multiplication, division must be performed in specific ways depending on what the
expected output is.
Example: Consider the following examples which shows a operations on two vectors a and b.

>> a = [1 3 5]
a =
1 3 5
>> b = [ 2 4 6]
b =
2 4 6
>> a + b
ans =
3 7 11
>> a - b
ans =
-1 -1 -1
>> a.*b
ans =
2 12 30
>> a * b’
ans =
44

Note: a.*b’ computes an element by element multiplication. b’ is the transpose of b and in this case
the result is the dot product of a and b.

2.7 Matrices

A matrix is similar to a vector in the sense that it is a collection of data referenced by a single identifier.
A matrix is two-dimensional rectangular array of data, with rows and columns.

2.7.1 Creating matrices:

Example: Create a matrix, A, that has two rows and three columns with specific values.

>> A = [ 1 2 4; 5 6 8]
A =
1 2 4
5 6 8

Example: Find the size of matrix, A.

>> size(A)

38
ans =
2 3

2.7.2 Accessing elements of a matrix:

Similar to a vector, elements of a matrix are accessed using indices. In the case of a matrices, the index
of each dimension must be specified to access the particular element. For example, in the case of a two
dimensional matrix, both the row index and the column index must be specified separated by commas;
row index first and the column index second.
Example: Assign the value of the 1st row, 2nd column of matrix A, to variable x.

>> x = A(1, 2)
x =
2

Example: Assign the value of the 2nd row, 3rd column of matrix A, to variable y.

>> y = A(2, 3)
y =
8

Example: Create a vector x that contains the first row and the last two columns of A.
>> x = A(1, 2:3)
x =
2 4
Example: Create a matrix B that contains the first two rows and the first two columns of A.
>> B = A(1:2, 1:2)
B =
1 2
5 6

2.7.3 Modifying elements of a matrix:

Similar to a vector, the elements of the matrix can be modified by directly assigning the value to the
appropriate index.
Example: Update the value of element on the 2nd row, 3rd column of matrix A to 9.

>> A(2, 3) = 9
A =
1 2 4
5 6 9

Example: Update the value of the element on the 1st row, 2nd column of matrix A to 50.

>> A(1, 2) = 50
A =
1 50 4

39
5 6 9

2.7.4 Matrix operations:

Similar to vectors, most of the mathematical and logical operations can be performed on matrices, but the
validity and the behavior of some operations will depend on the dimension of the matrices. For example,
matrix multiplication will only be valid if the matrix dimensions are such that they could be multiplied.
We will not go through these operations in detail in these notes, but you are encouraged to try them out
on MATLAB.

2.8 Cell Arrays:

Another useful type of data that is available in MATLAB (which is not available in many other program-
ming languages) is a cell array. Similar to vectors and matrices, a cell array can store a more than one
value, and these values are accessed using an index. However, unlike in vectors and matrices, cell arrays
can store different types of data.

Creating cell arrays

Example: Create a cell array that has the following values as its elements: 2, ’a’, ’hello’

>> x = {2, ’a’, ’hello’}

x =

[2] ’a’ ’hello’

Notice that curly braces are used as opposed to square brackets. Try using square brackets as in the case
of vectors with numbers and see what happens.
Example: Create a cell array that contains the names of the following shapes as its elements: cylinder,
cone, cube

>> x = {’cylinder’ ’cone’ ’cube’}

x =

’cylinder’ ’cone’ ’cube’

Accessing elements

Example: Display the third element of the cell array x in the above example.

>> x = {’cylinder’ ’cone’ ’cube’};


>> fprintf(’The third element of vector x is: %s\n’, x{3})
The third element of vector x is: cube

40
Updating elements

Example: Update replace the second element of cell array x with prism and display its value.
>> x = {’cylinder’ ’cone’ ’cube’};
>> x{2} = ’prism’;
>> fprintf(’The second element of vector x is: %s\n’, x{2})
The second element of vector x is: prism
Example: Add cone as the 4th element of the cell array and display it.

>> x{4} = ’cone’;


>> fprintf(’The second element of vector x is: %s\n’, x{4})
The fourth element of vector x is: cone

2.9 Summary

In this topic, you learnt how to do computations (calculations) in MATLAB, and then learnt how to
write simple MATLAB programs for performing computational tasks. We formally introduced variables,
identifiers, expressions and assignments. You learnt the top-down design approach for solving simple
problems, through writing a flowchart before writing the program. You also learnt some basic arithmetic
and logical operations available in MATLAB through built-in commands. You learnt how to manage
collections of values using vectors and matrices.

41
Chapter 3

Functions

In the previous topic, you learnt how to write MATLAB programs to perform simple computations or
calculations. In this topic, you will learn another fundamental programming capability, abstraction; cre-
ating self-contained modules. In MATLAB, the self-contained modules are called functions. MATLAB
functions can then be put together to build a MATLAB program. In fact, you have already used MAT-
LAB built-in functions for doing input-output, and also for mathematical operations. In this topic, you
will learn: how to design and implement your own functions.
Abstraction is the key programming feature that helps problem solving through the top-down design
approach.

3.1 Abstraction through functions

Abstraction is the process of creating self-contained, reusable, units of software with clearly defined:

• inputs;

• outputs; and

• behaviour

that can then be put together to solve complex problems.


In MATLAB, abstraction is achieved through functions.
You have already seen and used MATLAB built-in functions for problem solving.
In this topic you will learn how to create your own functions

3.2 Using MATLAB functions

MATLAB functions have the following general usage syntax:

[y1, y2, ...] = function_name(x1, x2, ....)

42
x1, x2, ... - input arguments
y1, y2, ... - output arguments

e.g.
> disp(’Hello World’);
> fprintf(’y = %f’, y);
> y = log(x);

• The number of input arguments can vary from 0 to any number.

• The number of output arguments can vary from 0 to any number.

• The type of data used as input arguments and output arguments can be any MATLAB data type
(e.g. Scalar variables, Vectors etc).

3.3 Creating and Testing MATLAB functions

If there is no pre-defined function for your needs, you can build your own.
Following is a generic template for creating a function:

function [y1, y2, ..] = function_name(x1, x2, ..)


% Comments to describe the function
statement_1
statement_2
.....
end

The first line of the function, which defines the function name along with the input and output parameters
is referred to as the function signature.
Note: The values of inputs and outputs when defining a function are referred to as parameters. The
actual values that are sent when calling the function are called arguments. Although not strictly correct,
these two words are often used interchangeably.
Input values of x1, x2, etc. are used in statements within the function to compute output values y1, y2
etc.
Let us implement some functions and run them to understand this better.
Problem Statement: Write a MATLAB function that returns the sum of two variables (Listing 3.1),
with the following signature.

function y = my_add(x1, x2)


% Input:
% x1, x2 - the two input values to the added
% Output:
% y - the sum of two values

Program Listing:
Listing 3.1 shows the program listing for the function which we have named my add.

43
Listing 3.1: my add.m
1
2 function y = my_add(x1, x2)
3 % my_add.m
4 % This function adds two input values x1 and x2
5 % and returns the result y
6 y = x1 + x2;
7

8 end

Explanation: This function has three non-comment lines, which are explained below.

• Line 1: This is the function signature, which defines the function name, input and output parame-
ters. The MATLAB keyword function at the start of the line, indicates that you are creating a
new function. In this case, the name of the function is my add, which takes two input parameters
x1 and x2 and returns one output parameter y.
• Line 6: This is the implementation of the function. In this case, we only have one line, but in
general the code for implementing the functionality goes in the body of the function.
• Line 8: This indicates the end of the function. Although this is optional, it is recommended that
you always use this.

Note: This is not a good example of a meaningful function because you can simply add two numbers
using the + operator in MATLAB, but used in this example to demonstrate a simple function.
Creating the Function:
Following are the steps to create a function in MATLAB.

1. Change the directory to where you want to save the function.


2. Open the MATLAB editor.
3. Type in the function in the editor.
4. Save to a file [function_name.m] (in the above example you must save the code in a file
my_add.m).
5. Test your function through a script file or command line. Note: A function must be called with the
appropriate input arguments

The function is now available to be used by your MATLAB scripts that are in the same directory.
Testing the Function:
The next important step is to test your function to ensure that it is doing what you expected it to do. In
order to do this, you are required to write a program that calls your function, and give different input
and output values and check if the function returns the value you expect it to return (or whatever else it
is expected to do, plot, save data in files etc). Such a program that is used to test a function is called a
driver program.
Program Listing:
A driver program to test the my_add function is shown in Listing 3.2.

44
Listing 3.2: my add driver.m
1 % my_add_driver.m
2 clear all;
3
4 a = input(’Enter first number ’);
5 b = input(’Enter second number ’);
6 c = my_add(a, b);
7

8 fprintf(’The sum of %d and %d = %d \n’, a, b, c);

Explanation:

• Line 2: This is a MATLAB command that clears all the variables that are in the workspace. It
is a good practice to include this at the start of programs (assuming they do not depend on any
variables that are in the workspace).

• Lines 4 and 5: Accept user input; the two numbers to be added, in this case.

• Line 6: Calls the function with the two input arguments (a and b), and the output of the function
is stored in variable c.

Note: Although the function signature had x1 and x2 as input parameters the arguments that were sent
to the function does not have to have the same identifiers (in this case we used a and b as the input
arguments). Same is true for the output parameters as you see in the example.
Program Output:

>> my_add_driver
Enter the first number 5
Enter the second number 6
The sum of 5 and 6 = 11

You must test your program for different input values, for example both positive, both negative etc.
Now we will look at an example of a function that returns two output values.
Problem Statement: Write a MATLAB function that returns the sum and the difference between two
variables.
Program Listing:
Listing 3.3 and 3.4 show the function and the driver programs.
A function to perform the problem statement above and the corresponding driver program are shown in
Listings 3.3 and 3.4 respectively.

Listing 3.3: my add sub.m


1

2 function [y1, y2] = my_add_sub(x1, x2)


3 % my_add_sub.m
4 % This function returns the sum (y1) and the differene (y2)
5 % of two input values x1 and x2
6 y1 = x1 + x2;

45
7 y2 = x1 - x2;
8 end

Listing 3.4: my add sub driver.m


1 % my_add_sub_driver.m
2 clear all;
3

4 a = input(’Enter the first number ’);


5 b = input(’Enter the second number ’);
6 [c, d] = my_add_sub(a, b);
7
8 fprintf(’The sum of %d and %d = %d \n’, a, b, c);
9 fprintf(’The difference of %d and %d = %d \n’, a, b, d);

Explanation
You should be able to understand the function and driver program without further explanation.
Program Output:

>> my_add_sub_driver
Enter the first number 6
Enter the second number 7
The sum of 6 and 7 = 13
The difference of 6 and 7 = -1

3.4 Important facts regarding MATLAB functions

Rule 1: Variables defined inside a function are not visible to the calling program, unless they are defined
as return parameters.
Consider the following modification in Listing 3.5 to the my_add function, where the addition is
computed but is not defined as an output value.

Listing 3.5: my add 1.m


1 function my_add_1(x1, x2)
2 % my_add_1.m
3 y = x1 + x2;
4 end

Consider the driver program in Listing 3.6.

Listing 3.6: my add driver 1.m


1 % my_add_driver_1.m
2 a = 5;
3 b = 6;
4 my_add_1(a, b)
5 fprintf(’The sum of %d and %d = %d\n’, a, b, y);

46
Program Output:

>> my_add_driver_1
Undefined function or variable ’y’.
Error in my_add_driver_1 (line 5)
fprintf(’The sum of %d and %d = %d\n’, a, b, y);

As you can see, the variable y, which was defined inside the function, but not returned, was not
available to the driver program.

Rule 2: Input values remain unchanged upon returning from the function regardless of changes to them
inside the function.
Consider the simple function shown in Listing 3.7 and the corresponding driver program shown in
Listing 3.8 and the output of the driver program.

47
Listing 3.7: my test.m
1 function my_test(x1)
2 % my_test.m
3 x1 = 2*x1;
4 end

Listing 3.8: my test driver.m


1 % my_test_driver.m
2 x1 = 5;
3 my_test(x1);
4 fprintf(’Value of x1 = %d\n’, x1);

Program Output:

>> my_test_driver
Value of x1 = 5

As you will notice variable x1, which was 5, was passed to the function my_test. The value of
x1 was changed within the function (to double the value). However, upon return, the value of x1
remained unchanged.
Rule 3: Input arguments to a function can be of any type, as long as they are valid and meaningful for
the commands in the function.
Consider the driver program in Listing 3.9 to which two vectors are sent as input values and the
output is a vector which is the addition of the two input vectors.

Listing 3.9: my add driver 2.m


1 % my_add_driver_2.m
2 a = [1 3 5];
3 b = [2 4 6];
4

5 c = my_add(a, b)

Program Output:

>> my_add_driver_2
c =

3 7 11

Note: Although this is true for MATLAB, this is not the case in many other programming lan-
guages; in many languages, the input and output parameters must be defined along with a type.

3.5 Features of a well designed function

Before we move to problem solving with functions, following are some guidelines to follow when de-
signing functions. These are good practices to follow rather than rules. Even if you do not follow these

48
guidelines your functions will still work, but your programs may not be well designed and, therefore,
will not be easy to maintain and test.

• A function should only do one specific task.

• If it does more than one task, consider splitting into multiple functions if possible.

• When designing functions think about reusability; a good function is one that is reusable and
self-contained.

3.6 Summary

In this topic you learnt how to create functions in MATLAB. Functions are self-contained, reusable units
of code that facilitate problem solving using the concept of abstraction; creating self-contained modules
of code that are designed for a particular purpose.

49
Chapter 4

Selection - Branching

So far you have learnt three fundamental programming capabilities:

• Input-output

• Calculation

• Abstraction

In this topic, you will learn another fundamental programming capability that is supported by program-
ming languages, making choices, also referred to as branching or selection.
Until now, we have seen programs that begin at the start, and execute each and every command in the
program sequentially, until the end is reached.
However, in problem solving it is common that in some cases, you have to do some actions only under
certain conditions. To accommodate this, programs have to perform certain actions based on the current
state of the system.
To deal with such cases, programs require flow of control or control flow; the ability to control the order
of the sequence of actions.
Branching is a form of flow of control that allows you to execute specific sections of the code while
skipping other sections of code.
Branching statements supported in MATLAB are:

• if-else and if-elseif

• switch

4.1 Branching with if-else

Almost all programming languages support branching using if and else statements, although the syn-
tax may vary slightly depending on the language. We will learn how to perform branching in MATLAB
programs.

50
4.1.1 if-else syntax and flow chart representation

Figure 4.1 (a) and (b) show two different forms of the branching statements, and Figure 4.1 (c) shows
the flowchart representation of a branching statement.

(a)

(c)
(b)

Figure 4.1: Branching flow chart and syntax.

Let us take a closer look at how the branching statement in MATLAB works.

When the if statement is executed:

• The control expression (cntrl_expr), also called the guard, is calculated.


• If the result of the cntrl_expr is non-zero (positive or negative), then the statements im-
mediately following the if statement up to the else (statement_1 and statement_2
in the example shown in Figure 4.1 (a)) are executed. If there is no else statement all
statements up to the end are executed (example shown in Figure 4.1 (b)).
• If the result of the cntrl_expr is zero, and an else clause exists, then the statements im-
mediately following the else clause up to the end (statement_3 and statement_4,
in this example) are executed.

cntrl_expr can be:

• an arithmetic or logic expression;


• a function; or
• a relational expression

4.1.2 Relational Expressions

You have learnt arithmetic, logic expressions and functions in the previous topics. We will now take a
look at the relational expressions. A relational expression in one that uses a relational operator.
Relational operators produce a logical result (1 or 0).

51
• a op b

• result is logical 1 (true), if the condition is true

• result is logical 0 (false), if the condition is false

Relational operators supported by MATLAB are shown in Table 4.1.

Operator Operation
== Equal to
˜= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Table 4.1: Relational Operators in MATLAB

We will now learn how to write MATLAB programs that require branching through a simple example.
Problem Statement: Write a MATLAB program to compute the area of a circle by accepting the radius
as user input. If the user enters an invalid radius (zero or negative) the program must print an error
message and exit.
Figure 4.2 shows the flowchart for this problem specification.

Figure 4.2: Flowchart for the program to calculate the area of a circle.

52
Program Listing:
Listing 4.1 shows a MATLAB program for the above problem statement.

Listing 4.1: CircleArea.m


1 % CircleArea.m
2 % This program computes the area of a circle
3 % Input: radius
4 % Output: area
5

6 % Prompt user for input


7 radius = input(’Enter radius(meters) ’);
8
9 % Compute area
10 if (radius <= 0)
11 disp(’Invalid radius’);
12 else
13 area = pi*radiusˆ2;
14 % Display a message on the console
15 fprintf(’Area = %f square meters\n’, area);
16 end

Note the indentation of the listing (lines 11, 13-15). The statements that are executed based on particular
states, are indented to improve the clarity of the program. Although it does not have an impact on the
execution of the logic, this is a good coding practice and must be followed.
Explanation:

• Line 10: The if clause makes the decision based on the expression; in this case radius <= 0,
which checks if the value of the radius entered by the user is less than 0. This expression will
return logical 1 (true) if the radius is less than 0 or equal to 0, and logical 0 (false) if the radius is
greater than 0.

• Line 11: This statement is executed only if the expression on line 10 returns a logical 1; in this
example if the radius is less than or equal to 0. If this statement executes, all the other statements
from else to end (line 12-16) are skipped.

• Line 12-16: The statements in lines 13-15 will be executed if logical 0 is returned; in this case,
the area will get computed and displayed.

Program Output:
>> CircleArea
Enter radius(meters) -8
Invalid radius
>> CircleArea
Enter radius(meters) 1
Area = 3.141593 square meters
Note: You must test your program at least for cases of both true and false conditions of the expres-
sion to make sure they work as expected.

53
4.1.3 Branching with if-elseif-else

Sometimes, when we are making choices, there are more than two options to choose from. In such cases,
an alternative selection statement available is the elseif statement, syntax shown in Figure 4.3.

Figure 4.3: Branching flow chart and syntax.

• Control expressions (cntrl_expr_1, cntrl_expr_2 etc) in executed in sequence, and if


the expression returns a non-zero value, the statements following in the particular control expres-
sion until the next control expression are executed in sequence, and the rest of the statements are
skipped.

• If multiple control expressions return a non-zero value, only the statements following the first
control expression that returned a non-zero value is executed.

For example, if cntrl_expr_1 returned a zero value, and cntrl_expr_2 returned a non-zero
value, only statement_3 and statement_4 will be executed. This will be the case, even if
cntrl_expr_3 also returned a non-zero value.
Problem statement: Write a program to simulate the following system. If VT is greater than VT R OR
VP is greater than VP R generate an alarm by setting AOU T to 1.
Figure 4.5 shows the flowchart for the problem.

54
Figure 4.4: Block diagram of a Chemical Process Alarm Generator.

Figure 4.5: Chemical Process Alarm Generator Flow Chart.

Program Listing:

Listing 4.2: AlarmGenerator.m


1 % AlarmGenerator.m
2 clear all;
3
4 % Prompt user for input
5 V_T = input(’Enter V_T ’);
6 V_P = input(’Enter V_P ’);
7 V_TR = input(’Enter V_TR ’);
8 V_PR = input(’Enter V_PR ’);
9

10 if V_T > V_TR

55
11 A_OUT = 1;
12 elseif V_P > V_PR
13 A_OUT = 1;
14 else
15 A_OUT = 0;
16 end
17

18
19 % Display output
20 fprintf(’A_OUT = %d\n’, A_OUT);

Explanation:
The program should be self explanatory if you are able to understand the logic in the flowchart in Fig-
ure 4.5.
Program Output:
>> AlarmGenerator
Enter V_T 50
Enter V_P 40
Enter V_TR 35
Enter V_PR 45
A_OUT = 1

>> AlarmGenerator
Enter V_T 50
Enter V_P 40
Enter V_TR 55
Enter V_PR 55
A_OUT = 0

Problem statement: Write a program to compute the following mathematical function.



2
x
 x≥1
f (x) = x −1 ≤ x ≤ 1 (4.1)

 3
x x < −1

Program Listing:
The output depends on the value of x. This requires us to choose the expression based on the value of x.
Listing 4.3 shows the program listing for this problem statement.

56
Listing 4.3: Compute fx 1.m
1 % Compute_fx_1.m
2 clear all;
3
4 % Prompt user for input
5 x = input(’Enter x ’);
6
7 if (x > 1)
8 y = xˆ2;
9 elseif ((x >= -1) && (x <= 1))
10 y = x;
11 elseif (x < -1)
12 y = xˆ3;
13 end
14
15 % Display output
16 fprintf(’f(x) = %f\n’, y);

Program Output:

>> Compute_fx_1
Enter x 2
f(x) = 4.000000

>> Compute_fx_1
Enter x -2
f(x) = -8.000000

>> Compute_fx_1
Enter x 0.5
f(x) = 0.500000

Problem statement: Write a program to compute the following mathematical function.





 x+y x ≥ 0, y ≥ 0
x + y 2

x ≥ 0, y < 0
f (x, y) = 2
(4.2)
x + y
 x < 0, y ≥ 0

x2 + y 2 x < 0, y < 0

Program Listing:
The output depends on the value of x and y. Listing 4.4 shows the program listing for this problem
statement.

57
Listing 4.4: Compute fx 1.m
1 % Compute_fxy_1.m
2 clear all;
3
4 % Prompt user for input
5 x = input(’Enter x ’);
6 y = input(’Enter y ’);
7

8 if ((x >= 0) && (y >= 0))


9 f = x + y;
10 elseif ((x >= 0) && (y < 0))
11 f = x + yˆ2;
12 elseif ((x < 0) && (y >= 0))
13 f = xˆ2 + y;
14 else
15 f = xˆ2 + yˆ2;
16 end
17
18 % Display output
19 fprintf(’f(x) = %f\n’, f);

Program Output:
>> Compute_fxy_1
Enter x 1
Enter y 2
f(x) = 3.000000
>> Compute_fxy_1
Enter x 1
Enter y -2
f(x) = 5.000000
>> Compute_fxy_1
Enter x -1
Enter y 2
f(x) = 3.000000
>> Compute_fxy_1
Enter x -1
Enter y -2
f(x) = 5.000000

4.1.4 Nesting if-else

if-else statements can be nested and multiple levels of nesting is possible. In the case of nested
if-else statements, the interpreter matches the end with most recent if statement. When writing
nested if-else statements having proper indentation is critical for improving the readability and un-
derstandability of the program, although indentation does not have an impact on the execution and the
output, as mentioned before.
Figure 4.6 shows the syntax of a single level nested if-else statement.
Program Listing:

58
Figure 4.6: Syntax for a single level of nested if-else.

Listing 4.5 shows the previous problem implemented with nested if-else statements.

Listing 4.5: Compute fx 2.m


1 % Compute_fxy_2.m
2
3 x = input(’Enter x ’);
4 y = input(’Enter y ’);
5

6 if (x >= 0)
7 if (y >= 0)
8 f = x + y;
9 else
10 f = x + yˆ2;
11 end
12 else
13 if (y >= 0)
14 f = xˆ2 + y;
15 else
16 f = xˆ2 + yˆ2;
17 end
18 end
19

20 fprintf(’f(x) = %f\n’, f);

Program Output:
The output of this program should be the same as the previous example.

59
4.1.5 Evaluating Expressions

Branching through an if-else statement depends on the value of the control expression following the
if or if-else condition.
When expressions are evaluated in MATLAB, there is a hierarchy for order of operations that are per-
formed as shown below:

• All arithmetic operators (BODMAS)

• All relational operators (==, ˜=, >, >=, <, <=) from left to right

• All ˜ operators

• All & and && are operated from left to right

• All |, || and xor operators are evaluated from left to right

If in doubt, use parentheses to change the default order of evaluation!

4.2 Branching with switch

An alternate way of branching is through the use of the switch statement.


It does not give any additional capabilities over the if-else statement, therefore the use of the switch
statement is a matter of personal choice. In some cases, the readability of the program could improve
from using the switch statement instead of the if-else statement.

Figure 4.7: Syntax for the switch statement.

We will try to understand the usage of the switch statement for branching, through a simple example.

60
Problem Statement: Write a program that could compute the volume of a cylinder or a cone, accepting
the height and the radius from the user; the program must allow the user to choose the shape: cone or
cylinder.
Program Listing:
Listing 4.6 shows the program listing.

Listing 4.6: ComputeVolume.m


1 % ComputeVolume.m - compute the volume of shapes
2 clear all;
3

4 % Prompt user for input


5 option = input(’Select shape, choose 1. Cylinder, 2. Cone: ’);
6 radius = input(’Enter base radius: ’);
7 height = input(’Enter height: ’);
8

9 switch option
10 case 1
11 volume = pi*radiusˆ2*height;
12 fprintf(’Volume of cylinder = %f\n’, volume);
13 case 2
14 volume = pi*radiusˆ2*height/3;
15 fprintf(’Volume of cone = %f\n’, volume);
16 otherwise
17 fprintf(’Invalid option: %option\n’, option);
18 end

Explanation:

• Lines 5 - 7: Accept user input from the keyboard.

• Line 9: switch keyword, with the value of the variable option is specified for the switch.

• Lines 10 and 13: Check for the two particular conditions, by checking the value of the variable
option which contains the user choice.

• Lines 11 and 12: These execute when the value of the option is equal to 1; in this case, the volume
of a cylinder is computed and displayed.

• Lines 14 and 15: These execute when the value of the option is equal to 2; in this case, the volume
of a cone is computed and displayed.

• Line 16: Defines the case for when none of the conditions are matched; in the case if the user
enters a value other than 1 or 2 the program will reach this line and will display the message on
Line 17.

Program Output:

61
>> ComputeVolume
Select shape, choose 1. Cylinder, 2. Cone: 1
Enter base radius: 10
Enter height: 5
Volume of cylinder = 1570.796327
ComputeVolume
Select shape, choose 1. Cylinder, 2. Cone: 2
Enter base radius: 10
Enter height: 5
Volume of cone = 523.598776

4.3 Summary

In this topic, you learnt how to make decisions, and selectively execute sections of code depending on a
condition. This is referred to as selection or branching and is one form of control flow in programming.
The MATLAB keywords you used for this purpose were, if-else-end, if-elseif-else-end
and switch-case-end. You also learnt how selection statements could be nested.

62
Chapter 5

Repetition - Looping

So far, you have learnt four fundamental programming capabilities:

• Input-output

• Calculation

• Abstraction

• Selection

In the previous topic, you learnt how to achieve control flow through branching; using the (if-else)
clause. Branching allows you to choose which block of code to execute, based on a certain condition,
but the flow of control in the program was still from top to bottom.
In this topic, you will learn a different form of control flow; doing repetitive actions, referred to as
looping.
Loops allow repeated execution of blocks of code.
We will learn two types of loops:

• while loops

• for loops

Let us first look at the motivation for loops in programs through a simple example.
Problem Statements: Write a program that displays all elements in a vector, along with the index of
each element.

63
Program Listing:
Listing 5.1 shows a program that prints the values of a vector x; this program does not use the looping
(repetition) capability in MATLAB.

Listing 5.1: WithoutLoop.m


1 % WithoutLoop.m
2 clear all;
3
4 x = [1 2 4 5 12];
5

6 fprintf(’x(1) = %d \n’, x(1));


7 fprintf(’x(2) = %d \n’, x(2));
8 fprintf(’x(3) = %d \n’, x(3));
9 fprintf(’x(4) = %d \n’, x(4));
10 fprintf(’x(5) = %d \n’, x(5));

Explanation:
The vector has five elements, and each element is printed using a fprintf statement, changing the
index from 1 to 5; there is a fprintf command to print each element.
Program Output:
>> WithoutLoop
x(1) = 1
x(2) = 2
x(3) = 4
x(4) = 5
x(5) = 12
Although this program perform the desired action, this is not the most elegant way of achieving this in a
computer program. Consider if the vector contained 100 or 1000 elements. Your program would require
as many lines as the number of elements in the vector, with each line having the correct index. Not only
is this a tedious task to do, but there is a high probability that you might type in a wrong index in a
particular line as the number of lines increase !
You will notice that in this program, each line executes the same command, fprintf, and the only
difference is the value of the index. In such cases, where mostly repetitive actions are required, with
a variation in the value used in the loop which can be computed, in this case incrementing the index,
looping is desirable. We will first look at how to accomplish this outcome using a while loop.

5.1 Using a while loop

Let us take a closer look at repetition using the while statement.


Figure 5.1 (a) and (b) show the syntax and the flowchart for the while loop respectively.

When the while statement is executed:

• The control expression (cntrl_expr), also called the guard, is calculated. This could be

64
(a)

(b)

Figure 5.1: while loop flow chart and syntax.

something the user enters, or the values could be read from a file as you will learn in the next
topic.
• If the result of the cntrl_expr is zero, the program comes out of the loop, (exits the loop)
executes the commands after the end statement.
• If the result of the cntrl_expr is non-zero (positive or negative):
– the statements immediately following the while statement up to the end statement
(statement_1 and statement_2) are executed.
– when the end statement is reached, the program returns to the while statement and re-
executes the cntrl_expr, and the next action will be determined based on the newly
computed result of the cntrl_expr.

The cntrl_expr can be:

• an arithmetic or logic expression


• a function
• a relational expression

Problem Statement: Write a program that displays all elements in a vector, along with the value of the
index, using a while loop.
Listing 5.2 shows a program for printing the elements in a vector using a while loop.

65
Program Listing:

Listing 5.2: WhileLoopExample1.m


1 % WhileLoopExample1.m
2 % Print element values of a vector
3 clear all;
4

5 x = [1 2 4 5 12];
6

7 indx = 1;
8 while indx <= length(x)
9 fprintf(’x(%d) = %d \n’, indx, x(indx));
10 indx = indx + 1;
11 end

Explanation:

• Line 3: This command clears all the current variables in MATLAB workspace (memory) for a
clean start to the program.

• Line 5: Define and initialize the vector, x, to be displayed.

• Line 7: Define a variable to access the elements of the vector, in this case indx, and initialize it
to 1, to start at the first element of the vector. Note that you can choose any variable name; I have
chosen indx to because this refers to the index, but it can be any name.

• Line 8: This is the while statement; The relational expression, indx < length(x), would
return a non-zero value when the value of the indx is less than the length of the vector given by
length(x), in this example it is 5. When the program first reaches the line, the value of the
indx will be 1 and therefore the expression will return a non-zero value, and the statements that
immediately follow the while (lines 9 and 10) will execute. If the value of indx becomes greater
than 5, the program will go to line 12; you will see how this happens in Line 10.

• Line 9: Print the value, based in the value of indx.

• Line 10: This is a very important line to understand. Here, the value of indx is incremented,
which will advance the loop in every repetition. When the indx reaches 6 in this case, the program
will exit the loop because the expression in Line 8 will return a zero. Therefore, the program will
repeat the statements within the loop, exactly 5 times.

• Line 11: End of loop.

Note: As you will notice, this program will print the values of all the elements of the vector regardless of
the length of the vector. In the case of the program that did not use a loop, we had to change the program
to add new fprintf statements, but in this case, you do not have to change the program because the
value length(x) will automatically make it loop for the length of the vector.
Program Output:
>> WhileLoopExample1
x(1) = 1

66
x(2) = 2
x(3) = 4
x(4) = 5
x(5) = 12
Note: Notice the indentation used when writing a loop. The statements are indented to make the code
more readable.
Now let us look at another example.
Problem Statement: Write a program that computes and displays the sum of all the elements in a vector,
using a while loop.
Program Listing:
Listing 5.3 shows a program for computing the sum of the elements in a vector using a while loop.

Listing 5.3: WhileLoopExample2.m


1 % WhileLoopExample2.m
2 % Find the sum of element values of a vector
3 clear all;
4
5 x = [1 2 4 5 12];
6

7 indx = 1;
8 total = 0;
9 while indx <= length(x)
10 total = total + x(indx);
11 indx = indx + 1;
12 end
13 fprintf(’total = %d \n’, total);

Explanation:
Most of the lines do not require an explanation because they are similar to the previous example. In this
case there is an additional variable, which we have named total which is used to store the sum of the
elements.

• Line 8: Initialize the total to 0.

• Line 10: Increment the value of the total by the value of element at the indx.

• Line 13: Print the final value of the variable total after exiting the loop.

Program Output:
>> WhileLoopExample2
total = 24
Note: In MATLAB, you do not have to write a program to compute the sum of a vector, because MAT-
LAB has a built-in function named, sum for this purpose, but this program is just for the purpose of
demonstrating looping through a simple example.

67
5.2 Using a for loop

MATLAB for loop uses the values of vector to loop through and, therefore, the vector for looping must
be first computed.
Figure 5.2 (a) and (b) show the syntax and the flowchart for the for loop respectively.

(a)

(b)

Figure 5.2: for loop flow chart and syntax.

When the for loop is executed, the statements in the for loop (starting from the command following
the for statement until the end statement) are executed repeatedly for a number of times equal to the
length of the vector. Each time the execution is repeated index is assigned the value of the vector
corresponding to the iteration.
The flowchat in Figure 5.2 (b) shows how the value of the index gets assigned in each repetition cy-
cle internally (the blocks shown in yellow are internal operation that occur within MATLAB; you as a
programmer do not have to do these actions).
Note: MATLAB for loop operation is somewhat different from many other programming languages.
In some other languages, the programmer has to explicitly write some of the logic in the yellow blocks
of the flowchart.
Problem Statement: Write a program that displays all elements in a vector, along with the value of the
index, using a for loop.
Program Listing:
Listing 5.4 shows a program for printing the elements of a vector using a for loop.

68
Listing 5.4: ForLoopExample.m
1 % ForLoopExample.m
2

3 clear all;
4
5 x = [1 2 4 5 12];
6 i = 1;
7 for indx = x
8 fprintf(’x(%d) = %d \n’, i, indx);
9 i = i + 1;
10 end

Explanation:

• Line 5: Initialize the vector.


• Line 6: Define a variable to hold the value of the index and initialize it to 1; in this case we have
used the variable i.
• Line 7: for statement iterates through the values of the vector x; each time the variable indx
gets the next value of the vector.
• Line 8: Display the index and the value of each element in the vector.
• Line 9: Increment the value of i by 1.

Program Output:
>> ForLoopExample2
x(1) = 1
x(2) = 2
x(3) = 4
x(4) = 5
x(5) = 12

5.3 Application of repetition

The ability to perform repetitive actions is one of the most powerful capabilities in programming that has
many real and useful applications in problem solving. You will next look at an application of looping
using an example you are familiar with; the same example we have used throughout these lectures, the
A/D converter.
Problem Statement: Write a program to simulate the sampler of an A/D converter for a given signal
v(t) = sin(t ∗ π/10)2 ; your program must repeatedly taken samples as every Ts = 1/fs time intervals.
Figure 5.3 show the block diagram of an A/D converter.
Figure 5.4 shows the input and output of the Sampler, the module we are interested in simulating in this
problem.
Let us consider the case where we are interested in sampling v(t) = sin(t ∗ π/10)2 from t = 0 to 10
seconds, every one second. Figure 5.4 shows the output of the sampler for this case. We will be storing
the output samples in a vector, v (you can choose any variable name for this).

69
Figure 5.3: Block diagram of an Analog to Digital Converter.

Figure 5.4: Sampler of an Analog to Digital Converter.

Listing 5.5 shows a program for simulating the sampler, without using loops.

Listing 5.5: SamplerWithoutLoops.m


1 % SamplerWithoutLoops.m
2 % v(t) = sin(t*pi/10)ˆ2 t=0 to 10s
3
4 clear all
5

6 v(1) = sin(0*pi/10)ˆ2;
7 v(2) = sin(1*pi/10)ˆ2;
8 v(3) = sin(2*pi/10)ˆ2;
9 v(4) = sin(3*pi/10)ˆ2;
10 v(5) = sin(4*pi/10)ˆ2;
11 v(6) = sin(5*pi/10)ˆ2;
12 v(7) = sin(6*pi/10)ˆ2;
13 v(8) = sin(7*pi/10)ˆ2;
14 v(9) = sin(8*pi/10)ˆ2;
15 v(10) = sin(9*pi/10)ˆ2;
16 v(11) = sin(10*pi/10)ˆ2;
17
18 v

70
Program Output:
>> SamplerWithoutLoops
v =
0 0.0955 0.3455 0.6545 0.9045 1.0000 0.9045 0.6545 0.3455
0.0955 0.0000
Although this program gives the desired result, it is not very flexible. If you were required to change the
sampling frequency, for example to take 10 samples every second rather than one sample a second, you
would have to rewrite the program with 101 statements, one for every sample! The action you are doing
in each line is more or less the same, except for the time incrementing in steps, in each line - therefore,
using loops is a better way of solving the same problem.

5.4 Sampler with a for loop

Listing 5.6 shows a program for simulating the sampler, using a for loop.

Listing 5.6: SamplerWithFor.m


1 % SamplerWithFor.m
2 % v(t) = sin(t*pi/10)ˆ2 t=0 to 10s
3

4 clear all;
5

6 % Define the time steps


7 T = [0:1:10];
8 i = 1;
9
10 for t = T
11 v(i) = sin(t*pi/10)ˆ2;
12 i = i + 1;
13 end
14 v

Now consider the same scenario, where you have to change the sampling frequency to take 10 samples
per second. All you would require is in this case is to change the vector T to [0:0.1:10].

71
5.5 Sampler with a while loop

Listing 5.7 shows a program for simulating the sampler, using a while loop.

Listing 5.7: SamplerWithWhile.m


1 % SamplerWithWhile.m
2 % v(t) = sin(t*pi/10)ˆ2 t=0 to 10s
3
4 clear all;
5 % Initialize time
6 t = 0;
7 index = 1;
8

9 % Loop while t <= 10


10 while t <= 10
11 v(index) = sin(t*pi/10)ˆ2;
12 index = index + 1;
13 t = t + 1;
14 end
15 v

Now consider the same scenario, where you have to change the sampling frequency to take 10 samples
per second. All you would require is in this case is to change the vector line 14 to t = t + 0.1.
Exercise: As you will remember, we looked at the A/D converter, when we were learning top-down
design followed by bottom-up implementation with functions. Listing 5.8 shows the template for the
sample_SinSquared function we designed at the time. Implement this function using a while or
a for loop.

Listing 5.8: sample SinSquared.m


1 function s = sample_SinSquared(t_s, t_e, f_s)
2 % This function samples a SinSquared signal and
3 % returns the samples as a vector s
4 % t_s: Start time
5 % t_e: End time
6 % f_s: Sampling frequency
7

8 % Code for sampling goes here


9

10 end

5.6 Which type of loop do I use (for or while)?

Both the for statement and the while statement can be used for repetition, but the choice depends on
the problem. Following are some guidelines that will help in your choice:

• for loops are generally used for known sequences (e.g. run the loop 11 times)

72
• while loops are used to process a block of code until a certain condition has been reached (e.g.
run the loop while time is ≤ 10)

We will look at an example to understand this better.


Problem Statement:
Fibonacci sequence is given by:

F (n) = F (n − 1) + F (n − 2).

The first two numbers are 0 and 1. Therefore, the sequence is:

0 1 1 2 3 5 8

1. Write a program that prints out the first 5 numbers of the Fibonacci Sequence

2. Write a program that prints out the Fibonacci Sequence up to 100

For the first problem, you could use a for or a while loop because you are expected to compute a
known number of values. Therefore, if you are using a for loop you can select a vector of known length
to iterate through.
In the second problem, you do not know how many numbers need to be computed (number of elements
in the Fibonacci Sequence up to 100). Therefore, you are not able to find a vector of the correct length
upfront to iterate through and, therefore, a for loop cannot be used in this problem.

5.7 Flow of Control within Loops

As you have now learnt, loop statements result in programs doing repeated actions, until a termination
condition is reached; termination is checked at the time the while or the for statement is executed.
However, in some programs it is necessary to:

• not continue repeating the actions when a certain condition is reached; or

• skip some statements under certain conditions.

break and continue are two statements that are useful in this context.
A break statement results in exiting the loop when the condition is reached.
A continue statement results in skipping the statements until the end statement, when the condition
is reached.

5.7.1 break statement

Figure 5.5 (a) and (b) show the syntax and the control flow for the break statement for the for loop
and the while loop respectively.
We will now look at an example where a break statement is used to exit a loop.

73
(a) (b)

Figure 5.5: Syntax of break statement.

Problem Statement: Write a program that will display the values of a vector, until a negative value is
reached; the program should display up to, including the last positive value.
Program Listing:
Listing 5.9 shows an example program that uses a break statement to solve the above problem.

Listing 5.9: WhileLoopExampleWithBreak.m


1 % WhileLoopExampleWithBreak.m
2 clear all;
3 x = [1 2 -4 5 12];
4 index = 1;
5
6 while index <= length(x)
7 if x(index) < 0
8 break;
9 end
10 fprintf(’x(%d) = %d \n’, index, x(index));
11 index = index + 1;
12 end

Explanation:

• Line 7: Checks for the condition for exiting the loop. In this example, the value of the element for
the index is checked to see if it is less than 0 (a negative value).

• Line 8: The break statement will cause the program to exit from the loop; in this case it will skip
lines 10-12, and execute command from line 13 onwards.

• Lines 10 - 12: These will execute as long as the break condition has not occurred.

Program Output:

74
>> WhileLoopExampleWithBreak
x(1) = 1
x(2) = 2

5.7.2 continue statement

Figure 5.6 (a) and (b) show the syntax and the flow control for the continue statement for the for
loop and the while loop respectively.

(a) (b)

Figure 5.6: Syntax of continue statement.

Problem Statement: Write a program that will display the values of a vector, skipping the negative
values.
Program Listing:
Listing 5.10 shows an example program that uses a continue statement to solve the above problem.

Listing 5.10: WhileLoopExampleWithContinue.m


1 % WhileLoopExampleWithContinue.m
2 clear all;
3 x = [1 2 -4 5 12];
4 index = 1;
5

6 while index <= length(x)


7 if x(index) < 0
8 index = index + 1;
9 continue;
10 end
11 fprintf(’x(%d) = %d \n’, index, x(index));
12 index = index + 1;
13 end

Explanation:

• Line 7: Checks for the condition for skipping the lines in the loop. In this example, the value of
the element for the index is checked to see if it is less than 0 (a negative value).
• Line 8: If condition is met, do whatever action is required in this condition. In this example, we
are incrementing the index so that we can print the next values of the loop.

75
• Line 9: The continue statement will cause the program to skip the lines through to the end of
the loop, just for that iteration of the loop and will return control to the while statement; in this
case it will skip lines 11-13, and return to line 6.

• Lines 11 - 13: These will execute as long as they are not skipped due to a continue condition.

Program Output:
>> WhileLoopExampleWithContinue
x(1) = 1
x(2) = 2
x(4) = 5
x(5) = 12

5.8 Nested Loops

Similar to selection statements, loop statements can be nested; a loop can occur within a loop.

• Both for and while loops can be nested.

• Multiple levels of nesting is possible

• Proper indentation will make code clear and readable

• When nesting, for and while loops can be mixed

Figure 5.7 (a) and (b) show the syntax and the flowchart for a nested while loop, with a single level
of nesting, respectively. Based on your understanding of the single while loop, these should be self-
explanatory.
Figure 5.8 (a) shows the syntax for a nested for loop. Figure 5.8 (b) shows the syntax for while loop
nested within a for loop.
Problem Statement: Write a program that displays the values of a matrix, A.

76
Figure 5.7: Nested while loop flow chart and syntax.

(a) (b)

Figure 5.8: Nested for loop and for-while loop syntax.

77
Program Listing:
Listing 5.11 shows a program that displays the values of a matrix A.

Listing 5.11: NestedForLoop.m


1 % NestedForLoop.m
2 clear all;
3
4 A = [1 2 4; 4 5 12];
5 [M N] = size(A);
6 m = [1:M];
7 n = [1:N];
8

9 for r_ind = m
10 for c_ind= n
11 fprintf(’A(%d,%d) = %d \n’,r_ind, c_ind, A(r_ind, c_ind));
12 end
13 end

Explanation:
As you see from this example, when you are using nested loops, you will need to maintain separate
indices for each loop; you will increment the index of the inner loop, while keeping the value of the
outer loop fixed. In this example we have two indices, r_ind and c_ind, for indexing the rows and the
columns of the matrix respectively. For each row index, you will loop through all values of the column
index before you increment the row index and repeat the same.

• Line 4: Define and initialize the matrix, in this case A, which is a 2 x 3 matrix.
• Line 5: Find the size of the matrix, M and N will be the number of rows and columns respectively
• Line 6: Define a vector, m, with the indices of the rows.
• Line 7: Define a vector, n with the indices of the columns.
• Line 9: Iterate through the values of the row indices.
• Line 10: For a selected value of the row index, iterate through the column indices.
• Line 11: Print the values of the matrix, using the appropriate indices.
• Line 12 and 13: The respective end statements for each loop.

Note: Notice the indentation used, which helps clearly identify the beginning and the end of the loop.
Program Output:
>> NestedForLoop
A(1,1) = 1
A(1,2) = 2
A(1,3) = 4
A(2,1) = 4
A(2,2) = 5
A(2,3) = 12

78
5.9 Loop Related Errors

Loops are a common place for program errors. Special attention should be paid to debug loop code.
The two most common kinds of loop errors are unintended infinite loops and off-by-one errors:

• An off-by-one error is when a loop repeats the loop body one too many or one too few times; this
usually results from a carelessly designed test expression

• Infinite loops are caused due to an expression that never reaches the termination clause;

5.10 Summary

In this topic you learnt how to perform repetitive actions in a program using looping; this is a form
of control flow in programs. You learnt the two types of looping statements available in MATLAB,
the while loop and the for loop. You learnt how to exit from loops under certain conditions, using
the break statement, and how to skip actions within a loop in some iterations, using the continue
statement. Finally, you learnt how to nest loops; loops within loops, called nested-loops.

79
Chapter 6

Input-output

You have already learnt basic input-output in MATLAB.


In particular, you have seen:

• How to get user input from the keyboard - console input

• How to write program output to the screen - console output

In the programs you have seen/written so far you have used these input-output capabilities.
However, many applications, including engineering problem solving applications, often require you to
process large amounts of data. In such cases, it is not practical to enter data manually through the
keyboard because it will be tedious, time consuming and error prone. Similarly, programs could generate
output, in large volumes, and in some cases this data needs to be further processed and analysed. In such
cases, it is not useful to merely display the results on the screen. Therefore, programs should have the
capability to read data from and write data to files on disk (or any other form of long term storage).
There are also cases where it is more meaningful to display the output as a plot (graph) rather then simple
text.
In this topic you will learn how to:

• Read data from files

• Write data to files

• Plot data and save them in files

6.1 Saving MATLAB results in a file

As you have seen so far, results generated from programs are assigned to variables which are stored in
the computer memory. In your programs so far, you displayed these values on the screen. However,
when you exit MATLAB, the values contained in memory (the values of the variables), will be lost. In
many practical applications, these results must be retained (persisted) for future use or analysis; storing
them in files is one mechanism for persisting data.

80
The save command/function is used to save the values of MATLAB variables, also referred to as data,
in a file. In our example, we will use the file extension .dat to refer to files used to store the data.
The following is the syntax for the save command.

save [filename] [data] [type]

Note: square brackets indicate parameter is optional.

Example 1: Save all variables in a MATLAB data file.

> save

All variables will be saved in a file named matlab.mat.


mat extension indicates that it is a MATLAB data file.
These variables can be read back to MATLAB using the load command as we will demonstrate
shortly.
Example 2: Save all variables in a MATLAB data file specifying a filename.

> save myData

All variables will be saved in a file named myData.mat.

Example 3: Save only a single variable matrix.

> A = [2 3; 4 5]
>> save A

Data gets stored in a file named A.mat.


Example 4: Save a matrix A, in a file named myData.dat, in ASCII format.

> A = [2 3; 4 5]
> save myData.dat A -ascii
> type myData.dat
2.0000000e+000 3.0000000e+000
4.0000000e+000 5.0000000e+000

Note: the type command lists the contents of the file. Such files can be read by non-MATLAB
programs as well.

6.2 Reading data form a file

Data saved from MATLAB can be read using the load command.
The load command reads a MATLAB file, all the data saved in the file will be loaded back into the
MATLAB workspace, with the original variable names.
The load command reads an ASCII file; all the data will be saved in a variable with name equal to the
file name.

81
Example 1: Save the workspace in a file named myData. Clear the variables and load the data back
into MATLAB workspace.

> A = [2 3; 4 5]
> B = [3]
> save myData
> clear
> who
> load myData
> who

Your variables are:

A B

Example 2: Save a matrix A in a file named myData.data in ASCII format. Clear the variables and
load the data back into MATLAB workspace.

> A = [2 3; 4 5]
> save myData.dat A -ascii
> clear
> who
> load myData.dat
> who

Your variables are:

myData

6.3 Lower level input/output functions

The load and save commands for reading from/writing to files are only possible when each line
of the data in the files is the same format and are numbers. In such cases, data can be read directly to a
matrix. However, this is too limiting in applications that require processing complex data (files that have
strings and the lines have different lengths).
In such cases, lower level input/output commands must be used to read from, and write to, files. These
lower level command require programming effort, as you will see shortly, but they provide more flexi-
bility and functionality in terms of file operations.
Using these commands for file input/output, the program must perform the following steps:

• Opening the file

• Reading from and/or writing to the file

• Closing the file

82
6.3.1 Opening files

Before data can be read from or written to a file, the program must explicitly open the file using the
fopen function in MATLAB.
Following is the syntax of the fopen command.

fid = fopen(’filename’, ’option’);

Input:

filename - name of the file to open.

option - r open for read only (this is the default) - w open for writing - a open for appending

Output:

fid - an identifier for the file to be used in later file operations. If the fid is -1, the open is not successful
and therefore further operations are not possible.

Example:

>> fid = fopen(’myData.dat’, ’r’)


fid =
3

This indicates that the file open was successful.

6.3.2 Closing files

Files opened in a program, must be closed after the read/write operations are completed, using the
fclose command.
Following is the syntax of the fclose command.

status = fclose(fid);

Input:

fid - valid identifier to a file previously opened using the fopen command.

Output:

status - indicates if the fclose operation was successful; status value of 0 indicates the opera-
tion was successful.

83
6.3.3 Reading from a file

Once a file is opened, you can use MATLAB commands associated with reading and writing to files to
perform appropriate read/write operations. MATALB supports a number of commands for reading data
from a file. The appropriate command must be chosen based on the type of file and the data to be read.
Following are some functions related to reading files.

• fgets: read a line at a time from a text file

• fscanf: read formatted data into a matrix

• textscan: read text data and store in a cell array

• feof: test for end-of-file

We will now learn how to use these commands through examples.

Reading a line at a time using fgets:

Problem Statement: Read a text file, named myText.txt which contains lines text, and print the text
on the screen.
Because the file needs to read a line at a time, you can use the fgets function.
Program Listing:
Listing 6.1 shows a program for the above problem statement.

Listing 6.1: FileReadFgets.m


1 % FileReadFgets.m
2

3 fid = fopen(’myText.txt’);
4 if (fid == -1)
5 disp(’File open failed’);
6 else
7 while feof(fid) == 0
8 data = fgets(fid);
9 fprintf(’%s’, data);
10 end
11 end
12 fclose(fid);

Explanation:

• Line 3: File is opened and fid is a file identifier that is used to access the file from that point. In
this example, a file with name myText.txt is opened.

• Line 4: Checks if the file was opened successfully. A value of -1 indicates that the file open was
not successful.

84
• Line 5: This line is only reached if the opening was not successful. In this case the program
displays a message to indicate this.

• Line 7: foef function checks if the end-of-file is reached; until it is reached the file is read line
by line.

• Line 8 - 10: Read a line at a time, using the fgets command and print each line.

• Line 12: File is closed because it is no longer in use.

Program Output:

>> FileReadFgets
Programming is fun!
I am enjoying MATLAB programming.
It is easy!

Reading a numerical values in a file to a matrix using fscanf:

Problem Statement: Numerical values shown below, are stored in a file named myNumbers.dat.
The data values are separated by spaces, and in this case, assume that we know the exact number of data
values in the file (in this case 12). Write a program that will read the data and store it in a matrix of size
two rows and six columns?
8.2 -7.5 9 4.3 9.8 6 9 -1 2.3 6 8 7
Program Listing:
Listing 6.2 shows a program for the above problem statement.

Listing 6.2: FileReadFscanf.m


1 % FileReadFscanf.m
2

3 fid = fopen(’myNumbers.dat’);
4 if (fid == -1)
5 disp(’File open failed’);
6 else
7 A = fscanf(fid,’%f\n’, [2 3])
8 end
9 fclose(fid);

Explanation:

• Line 7: fscanf function in Line 7 reads the file; Note the following:

– program does not have to loop until the end-of-file as in the case of the fgets file because
a single call of the fscanf command reads until the end-of-file.
– The second input to the function, the format string, %f in this case, specifies the type of data
in the file.

85
– The third input to the function, specifies the number of rows followed by the number of
columns for the output matrix; data is read in column order (observe the output to understand
the order). In this example, the data will be read to a matrix, with 2 rows and 6 columns.

Program Output:

>> FileReadFscanf

A =

8.2000 9.0000 9.8000 9.0000 2.3000 8.0000


-7.5000 4.3000 6.0000 -1.0000 6.0000 7.0000

Now consider the change that would be required to store the data in a matrix of size 3 x 4. You would
have to change the fscanf statement (line 7) to:
A = fscanf(fid,%f\n, [3 4])
In this case, the program output would be:

>> FileReadFscanf

A =

8.2000 4.3000 9.0000 6.0000


-7.5000 9.8000 -1.0000 8.0000
9.0000 6.0000 2.3000 7.0000

Behavior of the program should be intuitive from the program output.


What if the number of elements in the file is not known prior to reading? In this case, you should change
line 7 to:

A = fscanf(fid,’%f\n’, [2 inf])

This statement would read the file to a matrix with 2 rows, until the end of the file is reached. If the
number of elements is not a multiple of the number of rows, the missing elements of the matrix will be
set to 0.
For example, in the above example, if line 7 was replaced with,

A = fscanf(fid,’%f\n’, [5 inf])

then the program output would be:

A =

8.2000 6.0000 8.0000


-7.5000 9.0000 7.0000
9.0000 -1.0000 0
4.3000 2.3000 0
9.8000 6.0000 0

86
Reading a text data in file to an array using textscan:

Problem Statement: Consider a file named productData.dat which contains three fields, product
type, make and price, as shown below.
camera nikon 224.50
camera sony 250.99
TV sony 4500.00
Write a program to read the data.
Program Listing:
In this case, because the file contains text data you would use textscan function.
Listing 6.3 shows a program for the above problem statement.

Listing 6.3: FileReadTextscan.m


1 % FileReadTextscan.m
2
3 fid = fopen(’productData.dat’);
4 if (fid == -1)
5 disp(’File open failed’);
6 else
7 A = textscan(fid,’%s %s %f’)
8 end
9 fclose(fid);

Explanation:

• Line 7: The textscan function in Line 7 reads the file, until the end-of-file is reached.

– The second parameter to the function, the format string specifies the type of data in each
column (in this example %s %s %f specifies that the first two columns are strings and the
third is a floating point number)
– A is a cell array of size 1 x 3 .
– Elements in a cell array are accessed using curly braces.

Program Output: After running the program A will contain the data read from the file. Following is
how you access this text data stored in cell arrays.

• A1, A2, A3 have the data for each column.

>> A{1}
ans =
’camera’
’camera’
’TV’

87
• Individual elements in string columns are accessed with double curly braces.

>> A{1}{1}
ans =
’camera’
>> A{2}{3}
ans =
’sony’

• Individual elements in float type columns are accessed as follows.

>> A{3}(1)
ans =
224.5000

6.3.4 Writing to a file

To write to a file that is already open, you would use the fprintf function. You have already used
this function to print output to the screen. In the case of writing to a file, you can use the same function,
with the first input parameter set to the file identifier. The second parameter would be the format string,
similar to the case of screen output, and the following parameters are the variables which are substitutes
for the place holders in the format string (you have already seen this).
The syntax of the fprintf command is:
fprintf(fid, format string, var1, var2,.....)
Problem Statement: Given a vector, v, write a program that would write the index, and the correspond-
ing value of each of the elements to a file named myOutputData.dat. For example, if the vector
v = 1 5 7 8, myOutputData.dat must contain:
1 1
2 5
3 7
4 8
Program Listing:
Listing 6.4 shows a program for the above problem statement.

Listing 6.4: FileWriteFprintf.m


1 % FileWriteFprintf.m
2

3 fid = fopen(’myDataOut.dat’,’w’);
4 if (fid == -1)
5 disp(’File open failed’);
6 else
7 v = [1 5 7 8];
8 i = [1:length(v)];

88
9 for ind = i
10 fprintf(fid,’%d %d\n’, ind, v(ind));
11 end
12 end
13 fclose(fid);

Explanation:

• Line 3: In this case, we must open the file for writing, hence the second input argument to the
function ’w’.

• Line 7: Defines and initializes the vector with the data to be written to the file.

• Line 8: Initializes the index vector for iterating through the loop.

• Line 9: The data is written a row at a time, hence the for loop.

• Line 10: To write to the file you will use the fprintf command you are already familiar with;
the only difference here is the first input argument, which in this case in the file identifier for the
file to be written to; in this case fid.

Note: The fprintf command can write the vector to the file without a loop, but in this case we have
used a loop to demonstrate the how you would normally do it using programming logic.
Program Output: You can view the output of the file using the following command:

>> type myDataOut.dat

1 1
2 5
3 7
4 8

6.3.5 Plotting data

In engineering applications, it is often useful to visualize the data to get a better understanding of the
trends, optimum values etc. MATLAB provides many built-in functions for data visualization.
MATLAB supports a range of plot types. Following are some of them:

• line graphs

• bar and horizontal bar charts

• histograms

• stem plots

• area plots

• a range of three dimensional plots

89
We will learn the basic plot types through an example; you are expected to learn about different plot
options by reading the relevant help pages on commands.
Problem Statement: Draw a line graph and a stem plot of the function v = sin(t*2*pi/T) for
T = 10 and t varying from 0 to 10.
Program Listing:
Listing 6.5 shows a program for the above problem statement.

Listing 6.5: PlotSinCurve.m


1 % PlotSinCurve.m
2 clear all;
3 T = 10;
4 t = [0:0.2:10]
5 v = sin(t*2*pi/T);
6 figure;plot(t,v)
7 xlabel(’Time (sec)’);
8 ylabel(’Voltage (volts)’);
9 pl_name= sprintf(’%s’, ’splot’);
10 saveas(gcf, pl_name, ’jpg’)
11

12 figure;stem(t,v);
13 xlabel(’Time (sec)’);
14 ylabel(’Voltage (volts’);
15 pl_name= sprintf(’%s’, ’sstem’);
16 saveas(gcf, pl_name, ’jpg’)

Explanation:

• Line 4: Initializes the vector t, with x-axis values - in this example the vector contains values
from 0 to 10 in steps of 0.2 ([0 0.2 0.4 ....... 10]

• Line 5: Sets the vector v, with y-axis values - in this example the values computed based on the
equation v = sin(t*2*pi/T). Each element of the vector is a value that corresponds to the
value of vector t. Vectors t and v are of the same length (and must of be of the same length in
order to be able to plot).

• Line 6: figure command opens a new figure window. plot function draws a line graph with
the values of the first and second parameters as the x and y axis respectively (Figure 6.1).
• Lines 7 and 8: Places the respective labels on the graphs.

• Line 9: Initializes a variable with the file name for saving the graph, using the sprintf function
- sstem is the name of the file in this example.

• Line 10: Saves the current figure in JPEG format. The first parameter, gcf, is a special variable
in MATLAB which refers to the current figure. The second parameter is the file name and the third
parameter is the type of file - ’jpg’ implies JPEG in this example. You can find more information
about the available options through the help command for the saveas function.

• Line 12: In this case the values of the two vectors (same as in the previous graph) are plotted as
the stem plot (Figure 6.2).

90
• The rest of the lines should be clear from the above explanations.

Program Output:
Figures 6.1 and 6.2 show the two plots produced by Listing 6.5. The program also saves the two plots
as JPEG (.jpg ) files.

1 1

0.8 0.8

0.6 0.6

0.4 0.4
Voltage (volts)

Voltage (volts
0.2 0.2

0 0

-0.2 -0.2

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8

-1 -1
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10
Time (sec) Time (sec)

Figure 6.1: Line graph of v(t) Figure 6.2: Stem plot of v(t)

Following are some of the MATLAB plotting related commands. The usage and the function of these
commands are explained in detail through the help command.

Command Function
axis Set axis limits
grid Display grid lines
plot Generates xy plot
print Generates plot or saves
plot to a file
title Add a text title on top
xlabel Adds text label to x-axis
ylabel Adds text label to y-axis

Table 6.1: Basic Plotting Commands

Note: In addition to these command there is a range of colours, symbols and line types that can be chosen
for the plots, which is described in the help command for the plots.

6.4 Summary

In this topic you learnt how to read from and write to files using the low level input-output commands
in MATLAB. For low level read and write operations, you must first open the file before read/write
operations, using the fopen commands. Once the operations are complete, you must close the file
using the fclose operation. MATLAB provides a number of built-in functions for reading files in

91
Command Function
close Closes the current plot
close all Closes all plots
figure Opens a new figure window
gtext Enables label placement with mouse
hold Holds the current plot (new plots commands will be
plot over the current graph)
legend Adds a legend to the graph
refresh Redraws current figure window
set Specifies properties of objects such as axes
subplot Creates plots in subwindows
text Places string in figure

Table 6.2: Some Additional Plot Enhancement Commands

Command Function
bar Creates a bar chart
loglog Creates a log-log plot
polar Creates a polar plot
semilogx Creates a plot with x-axis on a log scale
semilogy Creates a plot with y-axis on a log scale
stem Creates a stem plot
hist Aggregates the data into equally spaced bins
histc Aggregates the data into unequally spaced bins

Table 6.3: Specialized Plot Commands

different ways. In particular, we looked at three such functions for reading files: fgets, fscanf and
textscan, and the fprintf command for writing data to files. Finally, we learnt how to plot data
using the various built-in functions supported by MATLAB.

92
Command Function
contour Creates a contour plot.
mesh Creates a three-dimensional mesh surface plot.
meshc Mesh combined with a contour plot.
meshz Mesh with vertical lines underneath.
plot3 Creates three-dimensional plots from lines and
points.
surf Creates a three dimensional surface plot.
zlabel Adds text label to z-axis.

Table 6.4: Some Three-Dimensional Plotting Commands

93
Chapter 7

Program Design

In this topic, you will learn: how to design and implement programs using the top-down design followed
by bottom-up implementation.

7.1 Bottom-up program implementation

In the previous topic you learnt the top-down design approach. As you will recall, following are the
steps involved in the top-down design approach:

Step 1: Break the solution down to smaller steps that are manageable - algorithm

Step 2: Refine each step until all the steps are small enough to manage

Step 3: Implement the refined steps (written as MATLAB code) and test each step

Step 4: Combine the steps and test the solution as a whole - we will learn how to do this for complex
applications using the bottom-up implementation strategy in the next topic.

Although top-down design involved refining the steps to smaller steps to manage, in the examples you
have looked at so far, due to their simplicity, you were able to implement (write MATLAB code) after
a single stage of break down, e.g converting Fahrenheit To Celsius, computing the surface area of a
cylinder. However, design problems solved through computer programs are often more complex, and
they require several steps of breaking down to refine them to a level that is suitable for implementation.
For such problems, a common approach to writing the program is through top-down design followed by
bottom-up implementation.
Abstraction is the key programming feature that helps problem solving through the top-down design
approach.

7.2 Top-down design and bottom-up implementation with functions

In the previous section you learnt how to implement functions and the features of a well designed func-
tion. If you know how to write the logic for the function, writing functions is a pretty straight forward

94
task. However, what is more challenging is identifying the appropriate functions to solve a problem,
such that they are well designed functions. In this section we will learn how to do this. However, it is
something that requires a lot of practice and experience, which you will gain only by writing programs
for solving problems.
We will look at one approach for designing functions: top-down design, followed by bottom-up imple-
mentation. Bottom-up implementation, refers to the approach of implementing smaller components and
then assembling them to solve the larger problem.
We will learn this through an example of a problem you are already familiar with; designing a program
to simulate an A/D Converter.
Problem Statement: Write a function that simulates an A/D Converter that converts an analog signal
v(t) = sin2 (t ∗ pi/10), to a digital output using a binary encoding scheme.
Let us step through the top-down design approach to decompose the problem.

Step 1: Break the solution down to smaller steps that are manageable
In the previous examples we looked at the use of a flowchart to breakdown the problem to man-
ageable steps. In this example, we will use a block diagram, although you could use a flow chart
for this problem as well.
At the highest level, the A/D converter can be represented by the single block with one input and
one output as shown in Figure 7.1.

Figure 7.1: Block diagram of an Analog to Digital Converter.

Figure 7.2 show the A/D converter operation split to two blocks, a Sampler that samples the analog
signal and a Digitizer that produces the digital output.

Figure 7.2: Block diagram of an Analog to Digital Converter.

Step 2: Refine each step until all the steps are small enough to manage
Based on our knowledge of the A/D converter, we know that digitizing analog sample, requires
quantization followed by encoding, which are two different tasks. Therefore, we can break this
step down to two steps as shown in Figure 7.3.
In this problem, we are at a stage, where each block now represent a specific task and therefore,
no further breakdown is required. Therefore, we will move to the next step.

95
Figure 7.3: Block diagram of the Digitizer.

Step 3: Implement the refined steps (written as MATLAB code) and test each step
We will now do the implementation in a bottom-up fashion (implement the smallest components
first), using a function for each block.

1. We will now design and implement a function for the Quantizer.


• Function name: Choose a meaningful name for the function. In this case I will choose
the name quantize.
Note that I chose the verb quantize rather than the noun Quantizer for my function
because the function performs an action.
• Outputs: The function will have one output, the quantized samples, which we will
represent as a vector a (because it contains more than one value).
• Inputs: From the diagram, it is clear that one input to this function is the analog samples,
which we will represent as a vector s (because it contains more than one value). The
next question you have to consider is, are there any other inputs that the quantization
action would require. Based on your knowledge about the A/D converter, you know that
it would require the minimum voltage of the signal (V_min), the maximum voltage of
the signal (V_max), and the number of quantization levels q.
Now we are ready to implement the function. Listing 7.1 shows the template for the function,
without the implementation. At this stage you must implement the function and test it.

96
Listing 7.1: quantize.m
1 function a = quantize(s, v_max, v_min, q);
2 % This function returns the quantized output
3 % as a vector (a)
4 % s: Vector of samples
5 % v_max: Maximum signal strength
6 % v_min: Minimum signal strength
7 % q: Number of quantization levels
8

9 % Code for quantization goes here


10 end

2. We will next design and implement a function for the Encoder:


• Function name: I will choose the name encode.
• Outputs: The function will have one output, the digital signal, which we will represent
as a vector d.
• Inputs: The function will have one input, the quantized signal, a. In this case we do
not require any other input, because this is a simple binary encoder. However, if we had
a more sophisticated encoder, for example, one that could encode based on different en-
coding schemes, you will require another input to specify the type of encoding scheme.
However, we will not consider this case in our example for simplicity.
Now we are ready to implement the function. Listing 7.2 shows the template for the function,
without the implementation. At this stage you will implement the function and test it.

Listing 7.2: encode.m


1 function d = encode(a);
2 % This function returns the digital output as a
3 % binary vector (d)
4 % a: Vector of quantized samples
5

6 % Code for binary encoding goes here


7 end

3. Given that we have implemented the two lowest level function, we will now move to the next
higher level, and implement a function for the Digitizer. As you see from the diagram, the
digitizer, uses the Quantizer and the Encoder.
• Function name: In this I will choose the name digitize.
• Outputs: The function will have one output, the digital signal, which we will represent
as a vector d.
• Inputs: The function will take as input the analog samples, s. However, in addition
it would require all the inputs of the quantizer as well, because it will call the function
quantize. Therefore, the minimum voltage (V_min), the maximum voltage of the
signal (V_max), and the number of quantization levels q will also be inputs to this
function.
Listing 7.3 shows the code for the digitize function.

97
Listing 7.3: digitize.m
1 function d = digitize(s, v_max, v_min, q);
2 % This function returns the digitized output
3 % as a vector (d)
4 % s: Vector of samples
5 % v_max: Maximum signal strength
6 % v_min: Minimum signal strength
7 % q: Number of quantization levels
8

9 % Quantize the analog signal


10 a = quantize(s, v_max, v_min, q);
11
12 % Encode the quatized signal
13 d = encode(a);
14 end

This function it then tested stand alone to make sure that it gives the expected behaviour.
4. We will next implement the Sampler., which is at the same level as the Digitizer.
• Function name: I will choose the name sample SinSquared.
Note: I chose this name rather than sample, because the sampler we are implementing
in this case is very specific, which can only sample the SinSquared signal, not a generic
sampler that can sample any signal.
• Outputs: The function will have one output, the analog sample, which we will place in
vector s.
• Inputs: The diagram shows that the input to the sample in v(t) the analog signal.
However, in this case because we are designing a sampler for a specific signal you do
not have to make this an input to the function. However the sampler would require three
other inputs: start time, t_s; end time, t_e; and the sampling frequency, f_s).
Listing 7.4 shows the template for the sample_SinSquared function.

Listing 7.4: sample SinSquared.m


1 function s = sample_SinSquared(t_s, t_e, f_s)
2 % This function samples a SinSquared signal and
3 % returns the samples as a vector s
4 % t_s: Start time
5 % t_e: End time
6 % f_s: Sampling frequency
7
8 % Code for sampling goes here
9

10 end

You must now implement and test this function stand alone.
5. Now you are ready to move to the next higher level and implement the A/D Converter for
the problem, which will use the Sampler and the Digitizer.
• Function name: I will choose the name AToD SinSquared.
• Outputs: The function will have one output, the digital signal d.

98
• Inputs: The inputs for the function must be all the inputs for the Sampler, as well as
all the inputs for the Digitizer (other than the analog samples which are input from the
Sampler). Therefore, the inputs are: start time, t_s; end time, t_e; the sampling
frequency, f_s; the minimum voltage of the signal,V_min; the maximum voltage of
the signal,V_max); and the number of quantization levels, q.
Listing 7.5 shows the implementation for the AToD_SinSquared function.

Listing 7.5: AToD SinSquared.m


1 function d = AToD_SinSquared(t_s, t_e, f_s, v_max, v_min, q)
2 % This function converts the analog signal v(t)
3 % sin2(t*pi/10), to a digital output (d) using a
4 % binary encoding scheme.
5 % t_s: Start time
6 % t_e: End time
7 % f_s: Sampling frequency
8 % v_max: Maximum signal strength
9 % v_min: Minimum signal strength
10 % q: Number of quantization levels
11

12 % Sample the Sin squared signal


13 s = sample_SinSquared(t_s, t_e, f_s)
14

15 % Digitize the analog samples


16 d = digitize(s, v_max, v_min, q);
17
18 end

Step 4: The solution is tested as a whole

Now that you have tested the units individually, you must now test the complete solution; the function-
ality of the A/D converter to ensure that it gives the correct output for Sin squared signal, for different
input values.

7.3 Summary

In this topic you learnt how to design functions for problem solving using the top-down design followed
by bottom-up implementation paradigm.

99
Bibliography

[1] Alistair Moffat. Programming, Problem Solving, and Abstraction with C. Pearson, 2013.

[2] Attaway. Stormy. MATLAB A PRACTICAL APPROACH. Elsevier, 2009.

100

Вам также может понравиться