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

Eeee3206-Matlab Programming-2023-2024

Uploaded by

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

Eeee3206-Matlab Programming-2023-2024

Uploaded by

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

MATLAB PROGRAMMING

Faculty/School: NAHPI Code: EEEE3206


Department: EEE Semester: Second
Course Title: MATLAB Programming Day/Time:
Instructors: Prof Nfah/ Engr. Taah Office/Hours:
Tel/Email: 671 915 698
LEARNING OUTCOMES

At the end of the course, students will:

• Develop skills to analyze and break down an engineering problem and solve it

algorithmically using MATLAB;

• Have an understanding of various programming constructs, including sequential,

conditional, and repetition structures and how they can be used to solve various

computational problem;

• Be able to define functional modules for programs in MATLAB; use matrices and vectors

(arrays) in MATLAB when addressing relevant engineering problem; and create programs

in MATLAB to address specific problem requirements using the logical structures.


Introduction
MATLAB is a mathematical and graphical software package with numerical, graphical, and
programming capabilities. The name MATLAB stands for MATRIX LABORATORY. MATLAB is primarily
a tool for matrix computations. It was developed by John Little and Cleve Moler of MathWorks, Inc. MATLAB
was originally written to provide easy access to the matrix computation software packages LINPACK and
EISPACK. MATLAB is a high-level language whose basic data type is a matrix that does not require
dimensioning. There is no compilation and linking as is done in high-level languages, such as C or FORTRAN.
Computer solutions in MATLAB seem to be much quicker than those of a high-level language such as C or
FORTRAN. All computations are performed in complex-valued double precision arithmetic to guarantee high
accuracy. MATLAB has a rich set of plotting capabilities. The graphics are integrated in MATLAB. Since
MATLAB is also a programming environment, a user can extend the functional capabilities of MATLAB by
writing new modules. MATLAB has a large collection of toolboxes in a variety of domains. Some examples of
MATLAB toolboxes are control system, signal processing, neural network, image processing, and system
identification. The toolboxes consist of functions that can be used to perform computations in a specific domain.

MATLAB consists of two linked parts Matlab editor and Simulink. The first part is the programming language,
which consists of basic programming constructs. The second part is the library of an enormous number of built-
in programs, called functions, that perform operations commonly required in many fields of engineering and
science. Hence MATLAB is indispensable for an engineering student’s academic and professional productivity.
MATLAB can work with a variety of data types, including integers, real numbers, complex numbers, characters,
and logic variables, which can all be organized into arrays and other structures. MATLAB is an interactive
system, where intermediate results can be accessed as programs are developed.

MATLAB is also a high-performance language for technical computing. It integrates computation,


visualization, and programming in an easy-to-use environment where problems and solutions are expressed in
familiar mathematical notation. Typical uses include:

▪ Math and computation


▪ Algorithm development
▪ Modeling, simulation, and prototyping
▪ Data analysis, exploration, and visualization
▪ Scientific and engineering graphics
▪ Application development, including Graphical User Interface building

1
CHAPTER 1: PROBLEM SOLVING AND PROGRAMMING
1.1 Introduction
Computer programming is the study of problems, the elaboration of a problem-solving process, and
the analysis of solutions that come out of the problem-solving processes. Given a situation, the goal is to
develop a step-by-step list of instructions for solving any instance of the problem that might arise. Algorithms
are finite processes that if followed will solve the problem. Algorithms are solutions and computer
programming can be seen as the study and the implementation of algorithms.

1.2 Problem solving


A computer is a very powerful and versatile machine capable of performing a multitude of different tasks, yet it has
no intelligence or thinking power. A computer performs many tasks exactly in the same manner as it is told to do. This
places responsibility on the user to instruct the computer in a correct and precise manner, so that the machine is able
to perform the required job in a proper way. A wrong or ambiguous instruction may sometimes prove disastrous.
In order to instruct a computer correctly, the user must have clear understanding of the problem to be solved. Apart
from this he should be able to develop a method, in the form of series of sequential steps, to solve it. Once the problem is
well-defined and a method of solving it is developed, then instructing the computer to solve the problem becomes
relatively easier task.
Thus, before attempt to write a computer program to solve a given problem. It is necessary to formulate or define the
problem in a precise manner. Once the problem is defined, the steps required to solve it, must be stated clearly in the
required order.
1.2.1. Steps Involved in Problem Solving
A computer cannot solve a problem on its own. One has to provide step by step solutions of the problem to the
computer. In fact, the task of problem solving is not that of the computer. It is the programmer who has to write down
the solution to the problem in terms of simple operations which the computer can understand and execute. Problem
solving begins with the precise identification of the problem and ends with a complete working solution
in terms of a program or software. In order to solve a problem by the computer, one has to pass though certain
stages or steps;

1. Understanding the problem: Here we try to understand the problem to be solved in totally. Before with the
next stage or step, we should be absolutely sure about the objectives of the given problem.
2. Analyzing the problem: After understanding thoroughly the problem to be solved, we look different ways
of solving the problem and evaluate each of these methods. The idea here is to search an appropriate
solution to the problem under consideration. The end result of this stage is a broad overview of the sequence of
operations that are to be carried out to solve the given problem ranging from basic function required to inputs
and outputs.
3. Developing an algorithm: Here the overview of the sequence of operations that was the result of
analysis stage is expanded to form a detailed step by step solution to the problem under consideration. This
solution is represented in natural language called an algorithm.

2
4. Coding and implementation: This stage of the problem solving is the conversion of the detailed sequence
of operations in to a language that the computer can understand. Alternatively, it involves transforming
algorithm to high level programming language (C++, Matlab etc). Here each step is converted to its
equivalent instruction or instructions in the computer language that has been chosen implementation
5. Testing and debugging: The program created should be tested on various parameters. The program
should meet the requirements of the user. It must respond within the expected time. It should
generate correct output for all possible inputs. In the presence of syntactical errors, no output
will be obtained. In case the output generated is incorrect, then the program should be checked for
logical errors, if any. The errors or defects found in the testing phases are debugged or rectified and
the program is again tested. This continues till all the errors are removed from the program.

1.2.2 A Systematic Approach to Defining a Problem


Defining the problem is the first step towards a problem solution. A systematic approach to problem definition,
leads to a good understanding of the problem. Here is a tried and tested method for defining (or specifying) any
given problem. It consists of dividing the problem into three (3) separate components:

(1) input or source data provided


(2) output or end result required
(3) processing: a list of what actions are to be performed
Example: A program is required to read three (3) numbers add them and print their total. It is usually
helpful to write down the three (3) components in a defining diagram as shown below:

Input Processing Output


Read: Num1, Total = Num1 + Num2 + Num3 Print: Total
Num2,
Num3

1.2.3 A general problem solving approach


Here is a rough outline of a general problem-solving approach is presented:
▪ Write out the problem statement including information on what you are to solve
▪ Make sure you are solving the real problem as opposed to the perceived problem.
▪ Define and name all variables and /or symbols. Show numerical values of variables, if known.
▪ Identify and Name;
- relevant principles, theories and equations
- system and subsystems
- dependent and independent variables
- known and unknowns
- inputs and outputs
- Other necessary information
▪ List assumptions and approximations involved in solving the problem.
3
▪ Question the assumptions and then state which ones are the most reasonable for your purposes.
▪ Check to see if the problem is either under-specified, figure out how to find the missing information.
▪ If over-specified, identify the extra information that is not needed.
▪ Relate problem to similar problem or experience
▪ Design an algorithm
▪ Evaluate and examine the solution.

Globally, the steps helping to design an algorithm for problem solving are as follow:

(1) Understand the problem (Do problem by hand. Note the steps)

(2) Devise a plan (look for familiarity and patterns)

(3) Carry out the plan (trace)

(4) Review the plan (refinement)

Problem Example: Find the average of a given set of numbers.


Solution Steps: Proceed as follows:
(1) Understanding the problem
(i) Write down some numbers on paper and find the average manually, Noting each step carefully e.g. given
a list say: 5, 3, 25, 0, 9
(ii) Count the numbers | How many? = 5
(iii) Add them up | 5 + 3 + 25 + 0 + 9 =42
(iv) Divide Result by numbers counted | 42/5 =8.4
(2) Devising a plan
Make note of NOT WHAT YOU DID in steps (i) through (iv), but HOW YOU DID IT. In doing so,
you will begin to develop the algorithm.

How do we count the numbers?


Starting at 0 i.e. set a variable named COUNTER to 0
Look at 1st number, add 1 to COUNTER
Look at 2nd number; add 1 to COUNTER and so on, until you reach the end of the list
How do we add numbers?
Let a variable named SUM be the sum of numbers in list. Set SUM to 0
Look at 1st number, add number to SUM
Look at 2nd number, add number to SUM and so on, until we reach end of list
How do we compute the average?
Let AVE be the average
Then AVE = total sum of numbers divided by the numbers counted: SUM divided by COUNTER
Identifying patterns, repetitions and familiar tasks. Familiarity: Unknown numbers to be input? i.e. n
Patterns: look at each number in the list
Repetitions: Look at a number, Add number to sum, Add 1 to counter
(3) Carrying out the plan
4
Check each step, consider special cases, Check result, and Check Boundary Conditions: i.e. what if the list is
empty? Division by 0? Are all numbers within the specified range? In this example, no range is specified - No
special cases.
Check result by tracing the algorithm with a list of numbers e.g. 7, 12, 1, 5, 13.
If list is empty, we do not want to compute average. Therefore, before calculating AVE, check if COUNTER
= 0 i.e. If COUNTER = 0 then AVE = 0

else AVE = SUM/COUNTER


(4) Review the plan
Can you derive the result differently? Can you make the solution more general?
Can you use the solution or method for another problem? e.g. average temperature or average grades
1.3 Algorithm
An algorithm is a sequence of steps to solve a particular problem or algorithm is an ordered set of
unambiguous steps that produces a result and terminates in a finite time. It may be possible to solve to
problem in more than one way, resulting in more than one algorithm. Algorithm has a definite beginning
and a definite end, and consists of a finite number of steps. The choice of various algorithms depends on
the factors like reliability, accuracy and easy to modify. The most important factor in the choice of algorithm is the time
requirement to execute it, after writing code in high-level language with the help of a computer. The algorithm
which will need the least time when executed is considered the best. An algorithm is often considered as first step to
writing a program. An algorithm should have the following characteristics
▪ Precision: Each instruction must be clear and unambiguous.
▪ Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after finite
number of steps
▪ Uniqueness: results of each step are uniquely defined and only depend on the input and the result
of the preceding steps.
▪ Input/output: Each algorithm must take zero, one or more quantities as input data produce one or more output
values. An algorithm can be written in English like sentences or in any standard representation sometimes,
algorithm written in English like languages are called Pseudo Code
Example
Area of Triangle: Write an algorithm to find the area of the triangle. Let b, c be the sides of the triangle ABC and β
the included angle between. The given sides;

Step 1: Input the given elements of the triangle namely sides b, c and angle between the sides β.
Step 2: Area = (1/2) *b*c* sin β
Step 3: Output the Area
Step 4: Stop.

5
Using their algorithmic thinking skills, the software designers or programmers analyse the problem and
identify the logical steps that need to be followed to reach a solution. Once the steps are identified, the need
is to write down these steps along with the required input and desired output. There are two common methods
of representing an algorithm: flowchart and pseudocode. Either of the methods can be used to represent an
algorithm while keeping in mind the following: It showcases the logic of the problem solution, excluding any
implementational details. It clearly reveals the flow of control during execution of the program
1.4 Flowchart
Flowchart is often considered as a blueprint of a design used for solving a specific problem. A flow chart is a
step by step diagrammatic representation of the logic paths to solve a given problem. By looking at a Flowchart
one can understand the operations and sequence of operations performed in a system.
The flowcharts are pictorial representation of the methods to be used to solve a given problem and help a great deal to
analyze the problem and plan its solution in a systematic and orderly manner. A flowchart when translated in to a proper
computer language, results in a complete program. Flowchart is diagrammatic /Graphical representation of
sequence of steps to solve a problem. To draw a flowchart following standard symbols are used;

Also called Terminator symbol,


It indicates where the flow starts and ends
Also called Action Symbol, it represents a process, action,
or a single step.

Also called Data symbol, this parallelogram shape is used to


input or output data
A decision or branching point, usually a yes/no or
true/false question is asked, and based on the answer, the
path gets split into two branches.
This represents remote connection points in the flowchart.
Connectors are named with letters/numbers
Arrows are used to show order of flow between the shapes

Examples
1. Write an algorithm to find the square of a number.
Before developing the algorithm, let us first identify the input, process and output:
- Input: Number whose square is required
- Process: Multiply the number by itself to get its square
- Output: Square of the number

Algorithm to find square of a number:


Step 1: Input a number and store it to num
Step 2: Compute num×num and store it in square
Step 3: Print square

6
2. Algorithm & Flowchart to find real roots of Quadratic Equations AX2+BX+C=0
Step-1 Start
Step-2 Input A,B,C
Step-3 DISC= B2 – 4 A * C
Step- 4 IF (DISC < 0) THEN Write Roots are Imaginary Stop
ENDIF
Step-5 IF (DISC==0) THEN
Write Roots are Real and Equal
X1 = - B/(2*A)
Write Roots are X1,X1
Stop
ENDIF
Step-6 IF (DISC >0)
Write Roots are Real and Unequal X1= (- B + SQRT(DISC)) /
(2*A) X2= (- B + SQRT(DISC)) / (2*A) Write Roots are X1,X2
Stop
END
1.5 Pseudo code
The Pseudo code is neither an algorithm nor a program. It is an abstract form of a program. It consists of
English like statements which perform the specific operations. It is defined for an algorithm. It does not use
any graphical representation. In pseudo code, the program is represented in terms of words and phrases, but
the syntax of program is not strictly followed.
The word “pseudo” means “not real,” so “pseudocode” means “not real code”. Following are some
of the frequently used keywords while writing pseudocode: INPUT, COMPUTE, PRINT,
INCREMENT, DECREMENT, IF/ELSE, WHILE, TRUE/FALSE...
Advantages: * Easy to read, * Easy to understand, * Easy to modify.
Example: Write an algorithm to display the sum of two numbers entered by user, using pseudocode.
Pseudocode for the sum of two numbers will be:

START
INPUT num1
INPUT num2
COMPUTE Result = num1 + num2
PRINT Result
STOP
Before writing codes in a high level language, a pseudocode of a program helps in representing the basic
functionality of the intended program. By writing the code first in a human readable language, the
7
programmer safeguards against leaving out any important step. Besides, for non-programmers, actual
programs are difficult to read and understand, but pseudocode helps them to review the steps to confirm that
the proposed implementation is going to achieve the desire output
1.6 Flow control
The flow of control depicts the flow of events as represented in the flow chart. The events can flow in a
sequence, or on branch based on a decision or even repeat some part for a finite number of times.

1.6.1 Sequence

Such algorithms where all the steps are executed one after the other are said to execute in sequence. However,
statements in an algorithm may not always execute in a sequence. We may sometimes require the algorithm to
either do some routine tasks in a repeated manner or behave differently depending on the outcomes of previous
steps.

1.6.2 Selection
In such situation there are several alternatives and any one of the alternatives is selected based on the outcome
of a condition. Conditionals are used to check possibilities. The program checks one or more conditions and
perform operations (sequence of actions) depending on true or false value of the condition. These true or
false values are called binary values. Generally, the ‘IF-THEN’ is used to represent branch control. Examples:
Let us write an algorithm to check whether a number is odd or even.

- Input: Any number


- Process: Check whether the number is even or not
- Output: Message “Even” or “Odd”
Pseudocode and the flowchart of the algorithm can be written as follows:

START
PRINT "Enter the Number"
INPUT number
IF number MOD 2 == 0 THEN
PRINT "Number is
Even"ELSE

STOP

Example: Let us write a pseudocode and draw a flowchart where multiple conditions are checked to
categorize a person as either child (<13), teenager (>=13 but <20) or adult (>=20), based on age specified:

8
- Input: Age
- Process: Check Age as per the given criteria
- Output: Print either “Child”, “Teenager”, “Adult”

1.6.3 Repetition (iteration, loop)


These kinds of structures are used when we want something to be done repeatedly, for a given number of
times. Likewise, emit a beep five times, add two 10 times to a number, subtract three from a number till the
result is zero. All these are examples of repetitions. In programming, repetition is also known as iteration
or loop. A loop in an algorithm means execution of some program statements repeatedly till some specified
condition is satisfied.

Example: Write pseudocode and draw a flowchart to accept 5 numbers and find their
average. The pseudocode and flowchart are as follow:

Step 1: SET count = 0, sum = 0


Step 2: WHILE count < 5,
Step 3: INPUT a number to num
Step 4: sum = sum + num
Step 5: count = count + 1
ENDWHILE
Step 6: COMPUTE average = sum/5
Step 7: PRINT average

In this example, a counter called “count” keeps track of number of times the loop has been repeated. After
every iteration of the loop, the value of count is incremented by 1 until it performs the set number of
repetitions, given in the iteration condition. There are situations when we are not aware beforehand
about the number of times a set of statements need to be repeated. Such requirement of unknown
number of repetitions are handled using WHILE construct. i.e: WHILE count is less that 5, REPEAT
Steps 3 to 5

Note: We can distinguish WHILE-DO (WHILE) loop and DO-WHILE loop. In a DO-WHILE loop, the
block of instructions to be repeated is executed first before the condition is tested.

When we know the number of time that the sequence of instructions will be repeated, the FOR construct
is used. The For Loop is a loop where a specific code is executed FOR a specified number of times. This loop
is constructed using three statements, first is the counter initialization, next is the condition to check it and
then there is an increment/decrement operation to change the counter variable. That is:
9
FOR variable IN RANGE (initial value, final value, increment/decrement operation)
Example: Write pseudocode to accept 5 numbers and find their average using a FOR statement. The
pseudocode is as follow:
Step 1: sum = 0;
Step 2: FOR count IN RANGE (0,4,+1)
Step 3: INPUT a number to num Step 4:
sum = sum + num

END FOR
Step 5: COMPUTE average = sum/5
Step 6: PRINT average
In the example above the FOR loop is used. FOR count ranging from 0 to 4, REPEAT Steps 3 to 4. The
rd
3 value in the FOR statement indicate the increment/decrement value. Here it is 1. Then count will
successively take the values 0,1,2,3,4

1.7 Programming Languages


1.7.1 Introduction
As the involvement of computer, automation and robotics growing in our daily life, programming becomes
highly required to control all of them. To control all of these systems and machines and take desired output by
them skilled programming languages is necessary. However, the area of programming language becomes how
much wide but it will be under one of the two categories of programming languages (i.e., Low-level language
and High-level language). In the early days of computing, language design was heavily influenced by the
decision to use compiling or interpreting as a mode of execution. Depending on tools such as compilation and
interpretation in order to get our written code into a form that the computer can execute. Code can either be
executed natively through the operating system after it is converted to machine code (via compilation) or can
be evaluated line by line through another program which handles executing the code instead of the operating
system itself (via interpretation).

1.7.2 Classification of Programming Languages


Programming languages are basically classified into two main categories; Low- level language and
High-level language. Every programming language belongs to one of these categories and sub-category.
1. Low level languages
Low-level languages are used to write programs that relate to the specific architecture and hardware of a
particular type of computer. They are closer to the native language of a computer (binary), making them
harder for programmers to understand. Programs written in low-level languages are fast and memory
efficient. However, it is nightmare for programmers to write, debug and maintain low-level programs. They
are mostly used to develop operating systems, device drivers, databases and applications that require direct

10
hardware access. Low level languages are further classified in two more categories – Machine language and
Assembly language.
▪ Machine language: Machine language is closest language to the hardware. It consists set of
instructions that are executed directly by the computer. These instructions are a sequence of binary
bits. Each instruction performs a very specific and small task. Instructions written in machine language
are machine dependent and varies from computer to computer.
▪ Assembly language: Assembly language is an improvement over machine language. Similar to machine
language, assembly language also interacts directly with the hardware. Instead of using a raw binary
sequence to represent an instruction set, assembly language uses mnemonics. Assembly language
uses a special program called assembler. The assembler translates mnemonics to specific machine
code.
Advantages of low-level languages

• Programs developed using low-level languages are fast and memory efficient.
• Programmers can utilize processor and memory in a better way using a low-level
language.
• There is no need of any compiler or interpreters to translate the source to machine code.
Thus, cuts the compilation and interpretation time.
• Low-level languages provide direct manipulation of computer registers and storage.
• It can directly communicate with hardware devices.
Disadvantages of low-level languages

• Programs developed using low-level languages are machine dependent and are not
portable.
• It is difficult to develop, debug and maintain.
• Low-level programs are more error-prone.
• Low-level programming usually results in poor programming productivity.
• A programmer must have additional knowledge of the computer architecture of a
particular machine, for programming in the low-level language.
2. High level languages
High-level languages are similar to the human language. high-level languages are programmers friendly,
easy to code, debug and maintain. it provides a higher level of abstraction from machine language. They
do not interact directly with the hardware. Rather, they focus more on the complex arithmetic operations,
optimal program efficiency and easiness in coding. Programs in a high-level language are written using
English statements (such as Python, Java, C++, etc). High-level programs require compilers/interpreters
to translate source code to machine language. We can compile the source code written in the high-level
language to multiple machine languages. Thus, they are machine independent language. High-level
languages are grouped into two categories based on the execution model – compiled or interpreted
languages. We can also classify high-level language several other categories based on the programming
paradigm.
11
▪ Procedural programming is a programming paradigm, based upon the concept of the procedure
call. Procedures, also known as routines, subroutines, or functions, simply contain a series of
computational steps to be carried out. Any given procedure might be called at any point during a
program's execution, including by other procedures or itself.
▪ Structured programming (sometimes known as modular programming) is a programming
paradigm aimed at improving the clarity, quality, and development time of a computer program
by making extensive use of the structured control flow constructs of selection (if/then/else) and
repetition (while and for), block structures, and subroutines. Structured programming is a subset
of procedural programming that enforces a logical structure on the program being written to make
it more efficient and easier to understand and modify Structured programming frequently employs
a top-down design model, in which developers map out the overall program structure into separate
subsections. Note, it is possible to do structured programming in any programming language.
▪ Object-oriented programming is a programming paradigm based on the concept of "objects",
which may contain data, in the form of fields, often known as attributes; and code, in the form of
procedures, often known as methods. A feature of objects is that an object's procedures can access
and often modify the data fields of the object with which they are associated. Thus, programmers
define not only the data type of a data structure but also the types of operations (functions) that can be
applied to the data structure. In this way, the data structure becomes an object that includes both
data and functions. In addition, programmers can create relationships between one object and
another.
Advantages of High-level language

• High-level languages are programmer friendly. They are easy to write, debug and maintain.
• It provides higher level of abstraction from machine languages.
• It is machine independent language.
• Easy to learn.
• Less error-prone, easy to find and debug errors.
• High-level programming results in better programming productivity.
Disadvantages of High-level language

• It takes additional translation times to translate the source to machine code.


• High-level programs are comparatively slower than low-level programs.
• Compared to low-level programs, they are generally less memory efficient.
• Cannot communicate directly with the hardware.
While writing a program, you might need to decide whether to use a compiled language or an interpreted
language for the program source code. Both types of languages have their strengths and weaknesses. Usually,
the decision to use an interpreted language is based on time restrictions on development or for ease of future
changes to the program. The terms interpreted language and compiled language are not well defined because, in
theory, any programming language can be either interpreted or compiled. In modern programming language
implementation, it is increasingly popular for a platform to provide both options.

12
An interpreted language is a type of programming language for which most of its implementations execute
instructions directly and freely, without previously compiling a program into machine-language instructions.
The interpreter executes the program directly, translating each statement into a sequence of one or more
subroutines, and then into another language (often machine code). Examples of some common interpreted
languages include Ruby, JavaScript, and Python. A compiler is a program that converts human-readable code
into computer-readable instructions—a process that only happens once in the lifespan of that code. Initially, it
takes a bit longer because the compiler has to rearrange, optimize, or “compile” object code first. Examples of
purely compiled languages include C, C++ and Go.
Modular Design of Programs
One of the key concepts in the application of programming is the design of a program as a set of units
referred to as blocks or modules. A style that breaks large computer programs into smaller elements
called modules. Each module performs a single task; often a task that needs to be performed multiple
times during the running of a program. Each module also stands alone with defined input and output. Since
modules are able to be reused, they can be designed to be used for multiple programs. By debugging each
module and only including it when it performs its defined task, larger programs are easier to debug
because large sections of the code have already been evaluated for errors. That usually means errors will be
in the logic that calls the various modules. Modular programming has generally evolved into object-oriented
programming. Programs can be logically separated into the following functional modules: Initialization,
Input, Input Data Validation, Processing, Output, Error Handling, Closing procedure

Advantages of the Top-Down Design Method


• It is easier to comprehend the solution of a smaller and less complicated problem than to grasp
the solution of a large and complex problem.
• It is easier to test segments of solutions, rather than the entire solution at once. This method allows
one to test the solution of each sub-problem separately until the entire solution has been tested.
• It is often possible to simplify the logical steps of each sub-problem, so that when taken as a whole,
the entire solution has less complex logic and hence easier to develop.
• A simplified solution takes less time to develop and will be more readable. The program will be easier
to maintain

13
CHAPTER 2; INTRODUCTION TO MATLAB
2.1 Introduction
MATLAB is a special-purpose computer program optimized to perform engineering and scientific calculations.
It started life as a program designed to perform matrix mathematics, but over the years it has grown into a flexible
computing system capable of solving essentially any technical problem. The MATLAB program implements
the MATLAB programming language and provides a very extensive library of predefined functions to make
technical programming tasks easier and more efficient
2.2 Starting MATLAB and desktop Environment
To start MATLAB on a Windows system, double-click on the MATLAB icon. You will then see the MATLAB
Desktop. The Desktop manages the Command window and a Help Browser as well as other tools. The default
appearance of the Desktop is shown in Figure 1.1. Five windows appear. These are the Command window in
the center, the Command History window in the lower right, the Workspace window in the upper right, the
Details window in the lower left, and the Current Directory window in the upper left.
When the MATLAB software is started, a window opens in which the main part is the Command Window.
In the Command Window, you should see the symbol: >>. The >> is called the prompt. In the Command
Window, MATLAB can be used interactively. At the prompt, any MATLAB command or expression can be
entered, and MATLAB will respond immediately with the result. But it is also possible to write programs
in MATLAB that are contained in script files or MATLAB code files
Note: The following commands can serve as an introduction to MATLAB and allow you to get help: demo,
help, lookfor and doc. The installed version of MATLAB with all its features can be verified by using
the command ver.

Figure 1.1 Desktop appearance of MATLAB


14
2.3 MATLAB fundamentals
1. Variables, constants and operators
To store a value in a MATLAB session, or in a program, a variable is used. One easy way to create a
variable is to use an assignment statement. The format of an assignment statement is

variablename = expression
The variable is always on the left, followed by the = symbol, which is the assignment operator, followed
by an expression. The expression is evaluated and then that value is stored in the variable. MATLAB uses a
default variable named ans if an expression is typed at the prompt and it is not assigned to a variable.

Note: Putting a semicolon at the end of a statement suppresses the output (display).
1.1 Variable name

In MATLAB, Variable names must follow some standards: The name must begin with a letter of the
alphabet. After that, the name can contain letters, digits, and the underscore character (e.g., value_1), but
it cannot have a space. MATLAB is case-sensitive, which means that there is a difference between upper- and
lowercase letters. There are certain words called reserved words, or keywords, that cannot be used as
variable names. Names of built-in functions should not be used as variable names. Additionally, variable
names should always be mnemonic, which means that they should make some sense. For example, if
the variable is storing the radius of a circle, a name such as radius would make sense;

1.2. Numerical expression

Expressions can be created using values, variables that have already been created, operators, built-in
functions, and parentheses. For numbers, these can include operators such as multiplication and functions
such as trigonometric functions. An example of such an expression is: 2*sin(1.4). The result of a numerical
expression can be assigned to a variable using the assignment operator (=). For example x=2*sin(1.4). This
instruction will compute the numerical value of the expressions 2*sin(1.4)and assign the result as the content
of the variable x.

1.3. Constant

Variables are used to store values that might change, or for which the values are not known ahead
of time. Most languages also have the capacity to store constants, which are values that are known ahead
of time and cannot possibly change. An example of a constant value would be pi, or π, which is 3.14159….
In MATLAB, there are functions that return some of these constant values, some of which include: pi, i, j,
inf.

1.4. Characters and strings

A character in MATLAB is represented using single quotes (e.g., ‘a’ or ‘3’). The quotes are necessary
to denote a character; without them, a letter would be interpreted as a variable name. The character

15
set includes all letters of the alphabet, digits, and punctuation marks; basically, all of the keys on a keyboard
are characters. MATLAB also handles character arrays, which are sequences of characters in single quotes,
and strings, which are sequences of characters in double quotes (e.g: “Hello”).

1.5. Operators

Some common operators used in MATLAB are:


- Arithmetic operators: addition (+), substraction (-), multiplication (*), division by (/), power (^)
- Relational operators: Equal (==), Not Equal (~=), less than (<), greater than (>), less than or equal (<=)
- Logical operators: And (&, &&), Or (|, ||), Not (~), Exclusive or (xor)
- Bitwise operators: bitwise AND, bitwise OR, bitwise XOR, NOT, bit complement, bitshift, etc.

2. Built-in functions and help

There are many built-in functions in MATLAB. The help command can be used to identify MATLAB
functions, and also how to use them. For example, typing help at the prompt in the Command Window
will show a list of help topics that are groups of related functions. This is a very long list; the most elementary
help topics appear at the beginning. To find out what a particular function does and how to call it, type help
and then the name of the function. E.g: the following will give a description of the absolute value function:
help abs

To call a function, the name of the function is given followed by the argument(s) that are passed to
the function in parentheses. Most functions then return value(s). For example, to find the absolute value of
-4, the following expression would be entered: abs(-4) which is a call to the function abs. The number
in the parentheses, the -4, is the argument. The value 4 would then be returned as a result.

3. Basic commands in MATLAB


Basic command are necessary to facilitate MATLAB command prompt

Command Description
clc Clears the Command window
clear Removes all variables from memory
clear var1 var2 Removes the variables var1 and var2 from memory
Quit/exit Stops MATLAB
who Lists the variables currently in memory
whos List the current variables and sizes and indicate if
they have imaginary parts

4. Vectors and matrices

Vectors and matrices are used to store sets of values, all of which are the same type. A matrix can be
visualized as a table of values. The dimensions of a matrix are r × c (pronounced “r by c.”), where r is
the number of rows and c is the number of columns. A vector can be either a row vector or a column vector.
If a vector has n elements, a row vector would have the dimensions 1×n and a column vector would have the
16
dimensions n×1. A scalar (one value) has the dimensions 1×1. Therefore, vectors and scalars are actually
just special cases of matrices. Here are some diagrams showing, from left to right, a scalar, a column vector,
a row vector, and a matrix:

The scalar is 1×1, the column vector is 3×1 (three rows by one column), the row vector is 1×4 (one row by
four columns), and the matrix is 2×3 (two rows by three columns). All of the values stored in these
matrices are stored in what are called elements.

MATLAB is written to work with matrices and so it is very easy to create vector and matrix variables,
and there are many operations and functions that can be used on vectors and matrices. A vector in MATLAB
is equivalent to what is called a one-dimensional array in other languages. A matrix is equivalent to a two-
dimensional array.

4.1. Creating vectors


4.1.1 Creating row vectors

There are several ways to create row vector variables. The most direct way is to put the values that you
want in the vector in square brackets, separated by either spaces or commas. For example, both of these
assignment statements create the same vector v:
>> v = [1 2 3 4]
>> v = [1,2,3,4]
Both of these create a row vector variable that has four elements; each value is stored in a separate
element in the vector. The vector is 1×4.

If, as in the preceding examples, the values in the vector are regularly spaced, the colon operator can be
used to iterate through these values. For example, 2:6 results in all of the integers from 2 to 6 inclusive:
>> vec = 2:6
>>vec = 2 3 4 5 6
In this vector, there are five elements; the vector is a 1×5 row vector. Note that, in this case, the brackets [ ]
are not necessary to define the vector. With the colon operator, a step value can also be specified by using
another colon, in the form (first:step:last). For example, to create a vector with all integers from 1 to 9 in
steps of 2:
>> nv = 1:2:9
>>nv = 1 3 5 7 9
The linspace function creates a linearly spaced vector; linspace(x,y,n) creates a vector with n values in
the inclusive range from x to y. If n is omitted, the default is 100 points.
>> ls = linspace(3,15,5)
>>ls = 3 6 9 12 15
Similarly, the logspace function creates a logarithmically spaced vector; logspace(x,y,n) creates a vector
with n values in the inclusive range from 10x to 10y. If n is omitted, the default is 50 points. For
17
example, logspace (1,4,4) creates a vector with four elements, logarithmically spaced between 101 and
104, or in other words 101, 102, 103, and 104.

>> logspace(1,4,4)
ans =
10 100 1000 10000
Note: In computing log, log(x) calculates the natural logarithm of x while log 10(x) calculates the logarithm
base 10 of x
4.1.2 Creating Column vectors
One way to create a column vector is to explicitly put the values in square brackets, separated by
semicolons (rather than commas or spaces):
>> c = [1; 2; 3; 4]
c=
1
2
3
4
There is no direct way to use the colon operator to get a column vector. However, any row vector created
using any method can be transposed to result in a column vector. In general, the transpose of a matrix
is a new matrix in which the rows and columns are interchanged. For vectors, transposing a row vector
results in a column vector, and transposing a column vector results in a row vector. In MATLAB, the
apostrophe (or single quote) is built-in as the transpose operator.
>> r = 1:3;
>> c = r'
c=
1
2
3

4.1.3. Referring to and Modifying Elements

The elements in a vector are numbered sequentially; each element number is called the index, or
subscript. In MATLAB, the indices start at 1. A particular element in a vector is accessed using the name
of the vector variable and the index or subscript in parentheses. For example, let’s consider a vector
new_vector defined as:
>> new_vector = [1 4 10 0 9 15 30]
new_vector =
1 4 10 0 9 15 30
The fifth element in the vector new_vector is a 9. That is:
>> new_vector(5)
ans =
9
18
A subset of a vector, which would be a vector itself, can also be obtained using the colon operator.
For example, the following statement would get the fourth through sixth elements of the vector new_vector
and store the result in a vector variable subset_new_vector:
subset_new_vector = new_vector(4:6)
subset_new_vector =
0 9 15
By referring to an existing index, a vector can be modified. For example the fifth element of the vector
new_vector can be modified to -5 as:
new_vector(5)=-5
new_vector =
1 4 10 0 -5 15 30
By referring to an index that does not yet exist, a vector can also be extended. The vector new_vector has
7 elements but can be extended to 10 if we precise the value of the tenth element as:
new_vector(10)=25
new_vector =
1 4 10 0 -5 15 30 0 0 25

4.2. Matrices
4.2.1 Creating Matrices

Creating a matrix variable is simply a generalization of creating row and column vector variables.
That is, the values within a row are separated by either spaces or commas, and the different rows are
separated by semicolons. For example, the matrix variable new_mat is created by explicitly entering values:
>> new_mat = [4 3 1; 2 5 6]
new_mat =
431
256
There must always be the same number of values in each row and each column of a matrix. Internal
rows can be created using the various methods provided above: linespace, logspace, colon operator, transposed,
etc. MATLAB also has several functions that create special matrices. For example, the zeros function creates
a matrix of all zeros and the ones function creates a matrix of all ones.
>> zeros(3)
ans =
000
000
000
>> ones(2,4)
ans =
1111
1111

19
4.2.2 Referring to and Modifying Matrix Elements
To refer to matrix elements, the row and then the column subscripts are given in parentheses (always the
row first and then the column). For example, this creates a matrix variable new_mat and then refers to the
value in the second row, third column of new_mat:
>> new_mat = [2:4; 3:5]
new_mat =
234
345
>> new_mat(2,3)
ans =
5
This is called the subscripted indexing. It is also possible to refer to a subset of a matrix. For example,
this refers to the first and second rows, second and third columns:
>> subset_new_mat = new_mat(1:2,2:3)
subset_new_mat =
34
45
Using just one colon by itself for the row subscript means all rows, regardless of how many, and using
a colon for the column subscript means all columns. For example, this refers to all columns within the first
row or, in other words, the entire first row:
>> new_mat(1,:)
ans =
234
This refers to the entire second column:
>> new_mat(:,2)
ans =
34
If a single index is used with a matrix, MATLAB unwinds the matrix column by column. This is
called linear indexing. For example:
>> new_mat(6)
ans =
5
The matrix new_matis developed as: [2 3 3 4 4 5]

Note: It is usually much better style when working with matrices to use subscripted indexing
An individual element in a matrix can be modified by assigning a new value to it.
>> new_mat = [2:4; 3:5];
>> new_mat(1,2) = 0
new_mat =
204
345
An entire row or column could also be changed. For example, the following replaces the entire second row
with values from a vector obtained using the colon operator.
20
>> new_mat(2,:) = 5:7
new_mat =
204
567
To extend a matrix, an individual element could not be added as that would mean there would no longer be
the same number of values in every row. However, an entire row or column could be added. For example,
the following would add a fourth column to the matrix new_matcreated previously.
>> new_mat(:,4) = [9 2]'
new_mat =
2049
3452
Note: Just as we saw with vectors, if there is a gap between the current matrix and the row or column
being added, MATLAB will fill in with zeros.

4.3. Operations on vectors and matrices


4.3.1. Vectors and matrices as arguments of functions
In MATLAB, an entire vector or matrix can be passed as an argument to a function; the function will be
evaluated on every element. This means that the result will be the same size as the input argument. For
example let us find the absolute value of all the elements of a matrix new_matdefined as:
>> new_mat = [0 4 -3; -1 0 2]
new_mat =
0 4 -3
-1 0 2
>> abs(new_mat)
ans =
043
102
Note: You also have some special functions such as min, max, sum, prod which are matrix and vector
based and respectively return the minimum value, maximum value, sum and product of all elements.

4.3.2. Scalar and array operations on vectors and matrices


Numerical operations can be done on entire vectors or matrices.
Scalar multiplication: A vector or a matrix can be multiplied by a number. For example, a matrix named
new_mat can be multiplied by 5 as: result=5*new_mat; This will result in multiplying all the elements
of the matrix by 5. This also goes for the division. result=new_mat/2; This will results to dividing all the
elements of the matrix by 2.
Array operations: These are operations that are performed on vectors or matrices term by term, or
element by element. This means that the two arrays (vectors or matrices) must be of the same size to
begin with. This is the case for array addition and subtraction operators.

However, for any operation that is based on multiplication (which means multiplication, division, and
exponentiation), a dot must be placed in front of the operator for array operations. For example, for the
exponentiation operator, ‘ . ^’ must be used when working with vectors and matrices, rather than just the

21
^ operator. Squaring a vector, for example, means multiplying each element by itself so the .^ operator must
be used. Similarly, the operator ‘.*’must be used for array multiplication and ‘./’ for array division.
4.3.3. Matrix multiplication

Matrix multiplication does not mean multiplying term by term; it is not an array operation. Matrix
multiplication has a very specific meaning. First of all, to multiply a matrix A by a matrix B to result in a
matrix C, the number of columns of A must be the same as the number of rows of B. If the matrix
A has dimensions m×n, that means that matrix B must have dimensions n×something; Let’s call it p. We say
that the inner dimensions (the n) must be the same. The resulting matrix C has the same number of rows as
A and the same number of columns as B (i.e., the outer dimensions m×p). In mathematical notation we have:

This only defines the size of C, not how to find the elements of C. The elements of the matrix C are
defined as the sum of products of corresponding elements in the rows of A and columns of B. That is:

In the following example, A is 2×3 and B is 3×4; the inner dimensions are both 3, so performing the matrix
multiplication A*B is possible (note that B*A would not be possible). C will have as its size the outer
dimensions 2×4. The elements in C are obtained using the summation just described. The first row of C
is obtained using the first row of A and in succession the columns of B.

For example, C(1,1) is 3×1+8×4+0×0 = 35. C(1,2) is 3×2+8×5+0×2 = 46,etc

In MATLAB, the *operator will perform this matrix multiplication:


>> A = [3 8 0; 1 2 5];
>> B = [1 2 3 1; 4 5 1 2; 0 2 3 0];
>> C =A*B
C=
35 46 17 19
9 22 20 5

22
CHAPTER THREE MATLAB PROGRAMMING
Introduction
Once a problem has been analyzed, and the algorithm for its solution has been written and refined,
the solution to the problem is then written in a particular programming language. A computer program
is a sequence of instructions, in a given language, which accomplishes a task. To execute or run a
program is to have the computer actually follow these instructions sequentially. MATLAB uses what are
called either script files or MATLAB code files, which have an extension on the file name of .m.

A script is a sequence of MATLAB instructions that is stored in a file with an extension of .m and
saved. The contents of a script can be displayed in the Command Window using the typecommand. The
script can be executed, or run, by simply entering the name of the file (without the .m extension).
Before creating a script, make sure the Current Folder is set to the folder in which you want to save your
files. This is an example of MATLAB script: The script is named circlescript.m, saved and executed (F5).

% This script calculates the area of a circle >>circlescript


Radius=
% First the radius is assigned 5
radius = 5 Area=78.5398
% The area is calculated based on the radius
area = pi * (radius^2)
Note: To put in a comment, simply type the %symbol at the beginning of a line,
3.1. Input/output
The previous script would be much more useful if it were more general; for example, if the value of the
radius could be read from an external source rather than being assigned in the script. Also, it would be
better to have the script print the output in a nice, informative way. Statements that accomplish these tasks
are called input/output statements (I/O).

3.1.1. Input statement and output statements


Input statements read in values from the default or standard input device. In most systems,
the default input device is the keyboard, so the input statement reads in values that have been entered by
the user. The simplest input function in MATLAB is called input. The input function is used in an assignment
statement. To call it, a character vector is passed that is the prompt that will appear on the screen, and
whatever the user types will be stored in the variable named on the left of the assignment statement. For
example:

>> rad = input('Enter the radius: ')


Enter the radius: 5
rad =
In case the user entered the number 5 for radius

23
If character or character vector input is desired, ‘s’must be added as a second argument to the input function:
>> letter = input('Enter a character: ','s') Enter a
char: g
letter = 'g'
Output statements display character arrays or strings and/or the results of expressions and can allow
for formatting, or customizing how they are displayed. The simplest output function in MATLAB is
disp, which is used to display the result of an expression or a string or character array without assigning any
value to the default variable ans. However, disp does not allow formatting. For example:

>> disp('Hello')
Hello

>> disp(4^15)
60
Formatted output can be printed to the screen using the fprintf function. For example:
>> fprintf('The value is %d, for sure!\n',4*15)

>>The value is 60, for sure!

To the fprintf function, first a string or character vector (called the format specifier) is passed that
contains any text to be printed, as well as formatting information for the expressions to be printed. The format
specifier can be either a string or a character vector;

%d for integer (it stands for decimal integer)


%f for float (real number)
%c for character (one character)
%s for string of characters
Putting all of this together now, we can implement a complete program (script) which calculates and prints
the area of a circle based on its radius. The code below is saved in an m-file named circleIO.m

% This script calculates the area of a circle


% It prompts the user for the radius
% Prompt the user for the radius and calculate >>circleIO
% the area based on that radius Notes: units in cm.
Enter the radius:
fprintf('Note: units in cm.\n')
3.9
radius = input('Enter the radius: ');
Circle with radius of 3.90cm, the
area = pi * (radius^2); area is 47.78cm squared
% Print all variables in a sentence format
fprintf('Circle with a radius of %.2f cm,\n',... radius)
fprintf('the area is %.2f cm squared\n',area)
24
3.1.2. Printing vectors and matrices
For vectors and matrices, even though formatting cannot be specified, the disp function may be easier to
use in general than fprintf because it displays the result in a straightforward manner. For example,
mat = [15 11 14; 7 10 13]
mat =
15 11 14
7 10 13
>> disp(mat)
15 11 14
7 10 13
>> vec = 2:5
vec =
2345
>> disp(vec)
2 345
3.2. Scripts to produce simple plots
MATLAB has many graphing capabilities. Customizing plots is often desired and this is easiest to
accomplish by creating a script rather than typing one command at a time in the Command Window.

3.2.1. Plot function


The following script, plotonepoint, plots one point. To do this, first values are given for the x and y
coordinates of the point in separate variables. The point is plotted using a red star (‘*’). The plot is then
customized by specifying the minimum and maximum values on first the x and then y-axes using the
function axis. Labels are then put on the x-axis, the y-axis, and the graph itself using the functions xlabel,
ylabel, and title. The following shows the contents of the script plotonepoint that accomplishes this. The x
coordinate represents the time of day (e.g., 11 a.m.) and the y coordinate represents the temperature (e.g., in
degrees Fahrenheit) at that time.
% This is a really simple plot of just one point!
% Create coordinate variables and plot a red '*'
x = 11;
y = 48;
plot(x,y,'r*')
% Change the axes and label them
axis([9 12 35 55])
xlabel('Time')
ylabel('Temperature')
% Put a title on the plot
title('Time and Temp')

25
To plot more than one point, x and y vectors are created to store the values of the (x,y) points. For example,
to plot the points first an x vector is created that has the x values and then a y vector is created with the y
values. Then the plot function is used with x and y as the input arguments as:

Plot(x,y)
>> x = 1:6;
>> y = [1 5 3 9 11 8];
>> plot(x,y)
Note: The points are plotted with straight lines drawn in between. Note also that the default color is a shade
of blue. Also, the axes are set up according to the data; there are so many parameters for the plot function
that can be customization

3.2.2. Customizing a Plot


Plots can be done in the Command Window, if they are really simple. However, many times it is desired
to customize the plot with labels, titles, and so on, so it makes more sense to do this in a script. Using the
help function for plot will show the many options such as the line types and colors. The LineSpec, or
line specification, can specify up to three different properties in a character vector or string, including the
color, line type, and the symbol or marker used for the data points.

The possible colors are: (b) blue, (g) green, (r) red, (c) cyan, (m) magenta, (y) yellow, (k) black, (w)
white. Either the single character listed above or the full name of the color can be used in the string to
specify the color. The plot symbols, or markers, that can be used are: (.) point, (o) circle, (x) x-mark, (+)
plus, (*) star, (s) square, (d) diamond, (v) down triangle, (^) up triangle, (<) left triangle, (>) right triangle,
(p) pentagram, (h) hexagram. Line types can also be specified by the following: (-) solid, (:) dotted,
(-.) dash dot, (–) dashed, (none) no line. If no line type is specified and no marker type is specified,
a solid line is drawn between the points.

t=[0:pi/1000:2*pi]; %creation of vector time (t)


x=sin(t); %calculation of x
y=cos(t); %calculation of y
plot(t,x,'r-','linewidth',2) %plot x(t)
hold on %more curves to be plotted
plot(t,y,'g-','linewidth',2) %plot y(t)
grid on % activate the grid
title('sinewave signals') % name the figure
xlabel('time (in sec)') % name the x-axis
ylabel('magnitudes of x and y’)% name the y-axis
legend('x(t)','y(t)') % name the curves (legend)
26
3.2.3. Simple Related Plot Functions
Other functions that are useful in customizing plots include clf, figure, hold, legend, and grid. Brief
descriptions of these functions are given here:

• clf: clears the Figure Window by removing everything from it.


• figure: creates a new, empty Figure Window when called without any arguments. Calling it as
figure(n) where n is an integer is away of creating and maintaining multiple Figure Windows
and of referring to each individually.
• hold: is a toggle that freezes the current graph in the Figure Window, so that new plots will be
superimposed on the current one. Just hold by itself is a toggle, so calling this function once
turns the hold on, and then the next time turns it off. Alternatively, the commands hold on
and hold off can be used.
• legend: displays strings or character vectors passed to it in a legend box in the Figure Window,
in order of the plots in the Figure Window
• grid: displays grid lines on a graph. Called by itself, it is a toggle that turns the grid lines on
and off. Alternatively, the commands grid on and grid off can be used.

Also, there are many plot types. In MATLAB, we can use plot types: stem, bar, stairs, histogram (hist)
and even 3D plots (plot3).

3. 3 User defined functions


In MATLAB, we can categorize functions as
follows:
• Functions that calculate and return one value
• Functions that calculate and return more than one value
• Functions that just accomplish a task, such as printing, without returning any values
We have already seen the use of many functions in MATLAB. We have used many built-in functions such
as sin, abs, etc. In this section, user-defined functions will be introduced. These are functions that the
programmer defines, and then uses, in either the Command Window or in scripts. There are several different
types of functions. For now, we will concentrate on the kind of function that calculates and returns a
single result.

3.3.1. Function definition


A function in MATLAB that returns a single result consists of the following:
The function header (the first line), comprised of: The reserved word function, the name of
the output argument followed by the assignment operator (=), as the function returns a result. The
name of the function (This should be the same as the name of the file in which the function is stored
to avoid confusion). The input arguments in parentheses, which correspond to the argument that
are passed to the function in the function call.

A comment that describes what the function does (this is printed when help is used)
27
The body of the function, which includes all statements and eventually the output argument.
end at the end of the function (note that this is not necessary in many cases in current versions
of MATLAB, but it is considered good style)
The general form of a function definition for a function that calculates and returns one value looks like
this:
File: functionname.m (same as the name of the function)
-----
function outputargument = functionname(input arguments)
% Comment describing the function
Statements here;
(These must include putting a value in the output argument)
end % of the function
Note: if the function returns more than one variable, brackets are used, for example;
function[x, y, z]=functionname(input arguments)
In order to apply this, let’s build a MATLAB function that will help us to calculate the total resistance
of a parallel association of two resistors and another one calculating the total resistance of a series association
of two resistors.

%File: in_par.m %File: in_ser.m


function Req = in_par(R1,R2) function Req = in_ser(R1,R2)
% Compute the total resistance % Compute the total resistance
% of a parallel association % of a series association
Req=R1*R2/(R1+R2); Req=R1+R2;
End End

3.3.2. Calling a function


Technically, calling the function is done with the name of the file in which the function resides.
To avoid confusion, it is easiest to give the function the same name as the file name. In the previous example,
the functions names are in_par and in_ser. They are respectively saved in files in_par.m and in_ser.m.
When used in a script or in the command window, the result returned from these function can also be
stored in a variable in an assignment statement; For instance let’s calculate the total resistances of the
following circuits.

28
(A) The computation of the total resistance in the circuit can be done by calling the in_par function. That is:
>>Rtot = in_par(1e3,1.5e3)
Rtot =
600
(B) The computation of the total resistance in the circuit can be done by calling the in_ser function. That is:
>>Rtot = in_ser(1e3,1.5e3)
Rtot =
2500
(C) The computation of the total resistance in the circuit can be done by calling the in_par function. That is:
>> Req1=in_par(1e3,1.5e3)
Req1 =
600
>> Rtot=in_par(Req1,2e3)
Rtot =

461.5385
Or in one instruction.
>> Rtot=in_par(2e3,in_par(1e3,1.5e3)) Rtot =
461.5385
To Do: Solve the case (D), (E) and (F) in a script file name resistance_circuit

29
3.4. Programming with MATLAB
3.4.1. Selection statements
In the scripts and functions, we have seen, every statement was executed in sequence. This is not
always desirable. We will see how to make choices as to whether statements are executed or not, and how to
choose between or among statements. The statements that accomplish this are called selection or branching
statements The MATLAB software has two basic statements that allow to make choices: the if statement
and the switch statement. The if statement has optional else and elseif clauses for branching. The if statement
uses expressions that are logically true or false. These expressions use relational and logical operators.

a. The ifstatement
The if statement chooses whether another statement, or group of statements, is executed or not.
The general form of the if statement is:

if (condition)
action;
end
A condition is a relational expression that is conceptually, or logically, true or false. The action is a
statement, or a group of statements, that will be executed if the condition is true. When the if statement is
executed, first the condition is evaluated. If the value of the condition is true, the action will be executed;
if not, the action will not be executed. Let’s consider the script below analyzing the state of a diode depending
on the applied voltage.

disp('vd-id characteristics of a Silicon diode')

Vd=input('Enter the value of the voltage Vd (in volts) : ')

if (Vd > 0.7)


disp('The diode is forward biased')
end
The result on the screen is as follows for a value which verifies the tested condition (vd=2V).
>>vd-id characteristics of a Silicon diode
Enter the value of the voltage Vd (in volts): 2
Vd =
2
The diode is forward biased
Note: When the condition is false nothing happen on the screen. If we want to add another statement to be
executed in case where the condition is false, we will need to add an else clause.

30
b. The if-elsestatement
The if statement chooses whether or not an action is executed. Choosing between two actions, or choosing
from among several actions, is accomplished using if-else, nested if-else, and switch statements. The if-else
statement is used to choose between two statements, or sets of statements

The general form is:


If (condition)
action1;
else

action2:
end
First, the condition is evaluated. If it is true, then the set of statements designated as “action1” is
executed, and that is the end of the if-else statement. If, instead, the condition is false, the second set of
statements designated as “action2” is executed, and that is the end of the if-else statement. The first set of
statements (“action1”) is called the action of the if clause; it is what will be executed if the expression is
true. The second set of statements (“action2”) is called the action of the else clause; it is what will be executed
if the expression is false. One of these actions, and only one, will be executed—which one depends on
the value of the condition.
Let’s make our example on the diode better. Now if the specified voltage is not greater than 0.6, the
program must display that the diode is reverse biased. This is the corresponding code.

disp('vd-id characteristics of a Silicon diode')


Vd=input('Enter the value of the voltage Vd (in volts) : ')
if (Vd > 0.6)
disp('The diode is forward biased')
else
disp('The diode is reverse biased')
end
The result on the screen is as follow for a value which will not verifies the tested condition (vd=0.25V)
>> vd-id characteristics of a Silicon diode
Enter the value of the voltage Vd (in volts): 0.25
Vd =
0.2500
The diode is reverse biased
c. Nested if-elsestatement
The if-else statement is used to choose between two actions. To choose from more than two actions, the if-
else statements can be nested, meaning one statement inside another. This the general form of such
structure.

31
if (condition1)
action1;

elseif (condition2)

action2;

elseif (condition3)
action3;
else
default_action
End

First, condition1 is evaluated, if true, action1 will be executed and that is the end of the nested if-else
statement. But if condition1 is false, condition2 will be evaluated. If condition2 is true, then action2 is
executed and that is the end of the nested if-else statement. If condition2 is false, then condition3 is evaluated.
If condition3 is true, action3 will be executed and that is the end of the nested if-else statement. If condition3
is false, the next condition will be evaluated and so forth. If all the conditions are false, then the default
action (under the else clause) will be executed. That is why we always need and else clause at the end
of the nested if-else statement. Thus, at the end only one of these actions will be executed.

In order to illustrate that, let’s consider the script below given the state of a SCR depending if the voltage
is greater than 0.6 or the gate current is applied. The SCR is ON if and only if it is forward biased and a
gate current is applied. The corresponding code is as follow:

disp('State of a SCR')
Vd=input('Enter the value of the voltage Vd (in volts): ')
Ig_applied=input('gate current Ig applied ? yes (1) | No (0) : ')
if (Vd > 0.6 & Ig==1)
disp('SCR is forward biased and ON (gate current applied)')
elseif (Vd > 0.6 & Ig==0)
disp('SCR is forward biased but OFF (no gate current applied)')
elseif (Vd <= 0.6 & Ig==1)
disp('SCR is reverse biased and OFF (gate current applied)')
else
disp('SCR is reverse biased and OFF (no gate current applied)')
end
If we input the voltage vd=3 and the gate current (1 for yes). We will obtain the following
result:
SCR is forward biased and ON (gate current applied)
To Do: test the other condition of this program to see its behavior and conclude
32
c. The switchstatement
A switch statement can often be used in place of a nested if-else or an if statement with many elseif clauses.
Switch statements are used when an expression is tested to see whether it is equal to one of several possible
values. The general form of the switch statement is:

switch switch_expression case


caseexp1

action1;
case caseexp2
action2;
case caseexp3
action

33
The switch statement starts with the reserved word switch and ends with the reserved word end. The
switch_expression is compared, in sequence, to the case expressions (caseexp1, caseexp2, etc.). If the
value of the switch_expression matches caseexp1, for example, then action1 is executed and the switch
statement ends. If the value matches caseexp3, then action3 is executed and, in general, etc. If the value of
the switch_expression does not match any of the case expressions, the action after the word
otherwise is executed (the default action) if there is an otherwise (if not, no action is executed). It is not
necessary to have an otherwise clause, although it is frequently useful. The switch_expression must be
either a scalar or a character vector.

The following program will use the switch statement to grade a quiz score given as input (argument). Type
the function in a file named switchletgrade.m and save it in the current directory.
function grade = switchletgrade(quiz)
% First, error-check
if quiz < 0 jj quiz > 10
grade = 'X';else
% If here, it is valid so figure out the
% corresponding letter grade using a switch switch quiz
case 10
grade = 'A';
case 9
grade = 'A';
case 8
grade = 'B';
case 7
grade = 'C';
case 6
grade = 'D';
otherwise
grade = 'F';end
end
Here are two examples of calling this function:
>> quiz = 15;
>> lg = switchletgrade(quiz)
lg =
'X'
>> switchletgrade(9)
ans =
'A

34
3.4.2. Loop Statements
There are two basic kinds of loops in programming: counted loops and conditional loops. A
counted loop is a loop that repeats statements a specified number of times (it is known how many
times the statements are to be repeated). A conditional loop also repeats statements, but ahead of time
it is not known how many times the statements will need to be repeated – all depend on a condition.

There are two different loop statements in MATLAB: the for statement and the while statement. In
practice, the
for statement is used as the counted loop, and the while is usually used as the conditional
loop.
In many programming languages, looping through the elements in a vector or matrix is a very
fundamental concept. In MATLAB, however, as it is written to work with vectors and matrices, looping
through elements is usually not necessary. Instead, “vectorized code” is used, which means replacing
the loops through arrays with the use of built-in functions and operators.

a. for-loop statement
The for statement, or the for loop, is used when it is necessary to repeat statement(s) in a script or
function, and when it is known ahead of time how many times the statements will be repeated. The
statements that are repeated are called the action of the loop. The variable that is used to iterate through
values is called a loop variable or an iterator variable. If a single letter is used it must be different from
i and j . In MATLAB both i and j are built-in constants. The general form of the for loop is:

for loopvar = range


action;
end
Where loopvar is the loop variable, “range” is the range of values through which the loop variable is to
iterate, and the action of the loop consists of all statements up to the end. The range can be specified
using any vector, but normally the easiest way to specify the range of values is to use the colon operator.
The script below will display all the integer numbers from 0 to 10 in a column.

for k = 0:1:10
fprintf('%d\n',k)
end
To Do: By using a for loop, write a program that will display the following pattern: 60 45 30 15 0
b. Nested forloop
The action of a loop can be any valid statement(s). When the action of a loop is another loop,
this is called a nested loop. This help to make a sweeping of range on two variables. The general form
of a nested for loop is as follows

for loopvarone = rangeone %outer loop


for loopvartwo = rangetwo %inner loop

35
actiontwo
end
end
The first for loop is called the outer loop; the second for loop is called the inner loop. The action of
the outer loop consists (in part; there could be other statements) of the entire inner loop.
To Do: By using nested for loops, write a script that will displays the following patterns
(A) ***** (B) * (C) *++++
***** ** **+++
***** *** ***++
***** **** ****+

c. whileloop statement
The while statement is used as the conditional loop in MATLAB; it is used to repeat an action when
ahead of time it is not known how many times the action will be repeated. The general form of the while
statement is:

while condition
action
end
The action, which consists of any number of statement(s), is executed as long as the condition is
true. The way it works is that first the condition is evaluated. If it is logically true, the action is executed.
So, to begin with, the while statement is just like an if statement. However, at that point the condition
is evaluated again. If it is still true, the action is executed again. Then, the condition is evaluated again. If
it is still true, the action is executed again. Then, the condition is....eventually, this has to stop!
Eventually, something in the action has to change something in the condition, so it becomes false.
The condition must eventually become false to avoid an infinite loop. (If this happens, Ctrl-C will exit
the loop.). The program below will display the integers from 0 to 10.

k=0;

while k <= 10
fprintf('%d\n',k)

k=k+1;

end

To Do: Write a script that will ask the user to input a number within the range 15 to 30 until he/her does
it.
36

You might also like