Eeee3206-Matlab Programming-2023-2024
Eeee3206-Matlab Programming-2023-2024
• Develop skills to analyze and break down an engineering problem and solve it
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
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.
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. 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.
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)
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;
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
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.
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”
Example: Write pseudocode and draw a flowchart to accept 5 numbers and find their
average. The pseudocode and flowchart are as follow:
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
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
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
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.
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;
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.
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
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.
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
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.
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
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.
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.
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).
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)
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;
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
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.
Also, there are many plot types. In MATLAB, we can use plot types: stem, bar, stairs, histogram (hist)
and even 3D plots (plot3).
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.
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.
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
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.
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:
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 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
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