Matlab Programming
Matlab Programming
EEEE3206
Adapted from
Pr. NFAH MBAKA Eustace
Dr. KAMDEM Paul
April 2024
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. Computer solutions in
MATLAB are 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 offers an
interactive system, where intermediate results can be accessed as programs are developed. You
can develop solutions of problems for application in other MATLAB programs.
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
MATLAB features a family of application-specific solutions called toolboxes. Very important
to most users of MATLAB, toolboxes allow you to learn and apply specialized technology.
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems. Areas in which toolboxes are
available include signal processing, control systems, neural networks, fuzzy logic, wavelets,
simulation, and many others
CHAPTER 1: PROBLEM SOLVING AND PROGRAMMING
1.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.
1. 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.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;
i- 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.
ii- 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.
iii- 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.
Page | 1
iv- 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
v- 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 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:
Page | 3
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
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.
Page | 4
2.1 Why do we need algorithms
A programmer writes a program to instruct the computer to do certain tasks as desired. The
computer then follows the steps written in the program code. Therefore, the programmer first
prepares a roadmap of the program to be written, before actually writing the code. Without a
roadmap, the programmer may not be able to clearly visualise the instructions to be written and
may end up developing a program which may not work as expected. Such a roadmap is nothing
but the algorithm which is the building block of a computer program. Writing an algorithm is
mostly considered as a first step to programming. Once we have an algorithm to solve a
problem, we can write the computer program for giving instructions to the computer in high level
language (MATLAB for example). If the algorithm is correct, computer will run the
program correctly, every time. So, the purpose of using an algorithm is to increase the
reliability, accuracy and efficiency of obtaining solutions.
Page | 5
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
Example: Write an algorithm to display the sum of two numbers entered by user, using both
pseudocode. Pseudocode for the sum of two numbers will be:
START
INPUT num1
INPUT num2
COMPUTE Result = num1 + num2
PRINT Result
STOP
Page | 6
2.2.3 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
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:
- Input: Age
- Process: Check Age as per the given criteria
- Output: Print either “Child”, “Teenager”, “Adult”
Page | 7
Pseudocode is as follows:
START
INPUT Age
IF Age < 13 THEN
PRINT "Child"
ELSE IF Age < 20 THEN
PRINT "Teenager"
ELSE
PRINT "Adult"
STOP
END WHILE
Page | 8
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:
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;
END FOR
Page | 9
3. Programming Languages
3.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).
Page | 10
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.
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.
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.
3.3 Programming Paradigm.
3.3.1 Object-oriented programming
I t 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.s
3.3.2 Procedural programming
It is a programming paradigm, derived from structured programming, 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.
Page | 11
model, in which programmer map out the overall program structure into separate subsections.
A defined function or set of similar functions is coded in a separate module or sub module
which can be reused in other programs. After a module has been tested individually, it is then
integrated with other modules into the overall program structure.
[Link] 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
[Link] Advantages of the Top-Down Design Method
Page | 12
CHAPTER 2: INTRODUCTION TO MATLAB
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.1 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
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).
i. 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;
Note: The commands who and whos show variables that have been defined in the current
Command Window
clear clears out all or specified variables so they no longer exist in the workspace.
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 assign 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.
iii. 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.
Page | 14
iv. 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 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”).
v. 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.
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.
Page | 15
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.
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:6results in all of the
integers from 2 to 6 inclusive:
>> vec = 2:6
vec =
23456
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 =
13579
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 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 =
Page | 16
10 100 1000 10000
2.2.4. Matrices
i. 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
Page | 18
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.
>> 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
Page | 19
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.
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 ^ 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.
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.
Page | 21
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.
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).
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:
Page | 22
If character or character vector input is desired, ‘s’ must be added as a second argument to the input
function:
>> disp('Hello')
Hello
>> disp(4^15)
60
Formatted output can be printed to the screen using the fprintf function. For example:
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;
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
>> circleIO
% This script calculates the area of a circle
Note: units in cm.
% It prompts the user for the radius
% Prompt the user for the radius and calculate Enter the radius:
% the area based on that radius
3.9
fprintf('Note: units in cm.\n')
radius = input('Enter the radius: '); Circle with a radius of 3.90 cm, the
area = pi * (radius^2); area is 47.78 cm 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)
Page | 23
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,
Page | 24
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
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.
x=sin(t); %calculation of x
y=cos(t); %calculation of y
Page | 25
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:
In MATLAB, we can use plot types: stem, bar, stairs, histogram (hist) and even 3D plots (plot3)
% Create a grid
z = membrane(1, 50);
mesh(z)
colormap(jet)
title(' 3d logo')
axis tight
Page | 26
3.3. User defined functions
▪ 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)
▪ 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:
Page | 27
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.
(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 :
Page | 28
>>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.m
Page | 29
CHAPTER FOUR: MATLAB PROGRAMMING
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.
4.1.1. 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
end
The result on the screen is as follow for a value which verifies the tested condition
(vd=2V).
Vd =
2
The diode is forward biased
Page | 30
Note: When the condition is false nothing happen on the screen. If we want to add another
statements to be executed in case where the condition is false, we will need to add an else
clause.
4.1.2. 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 end
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.
else
end
The result on the screen is as follow for a value which will not verifies the tested condition
(vd=0.25V)
Page | 31
Enter the value of the voltage Vd (in volts): 0.25
Vd =
0.2500
disp('State of a SCR')
Page | 32
disp('SCR is forward biased but OFF (no gate current applied)')
else
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 conclud
4.1.3. 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
action3;
...
otherwise
default_action
end
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.
Page | 33
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.
>> lg = switchletgrade(quiz)
lg =
'X'
>> switchletgrade(9)
ans =
'A’
Page | 34
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.
4.2.1. forloop 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:
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 OK
Page | 35
for loopvarone = rangeone %outer loop
for loopvartwo = rangetwo %inner loop
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:
while condition
action
end
The action, which consists of any number of statement(s), is executed as long as
the condition istrue. 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.
Page | 36