0% found this document useful (0 votes)
35 views45 pages

ELE 562 Slide-Final

The document discusses the introduction and basics of MATLAB including its advantages and disadvantages, user interface, saving and loading files, file naming constraints, and starting with MATLAB either using the command window or m-files. MATLAB is a numerical computing environment and programming language with tools for computation, visualization, and more.

Uploaded by

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

ELE 562 Slide-Final

The document discusses the introduction and basics of MATLAB including its advantages and disadvantages, user interface, saving and loading files, file naming constraints, and starting with MATLAB either using the command window or m-files. MATLAB is a numerical computing environment and programming language with tools for computation, visualization, and more.

Uploaded by

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

15/03/2021

USE OF ENGINEERING SOFTWARE PACKAGES


[ELE 562, 2C]

Department of Electrical and Electronics Engineering


University of Ilorin, Ilorin
Oladimeji Ibrahim, PhD
Department of Electrical and Electronics
Engineering, University of Ilorin, Ilorin
Email: [email protected]
Office Address: Block 10, Ground Floor
H/P: +2348062421820

January, 2021

ELE 562
Course Outline

Introduction to MATLAB and their engineering applications

Introduction to AUTOCAD and their engineering applications

Introduction to Simulation Packages

15-Mar-21
2

1
15/03/2021

1.0 Introduction to MATLAB

MATLAB

 MATLAB stands for MATrix LABoratory and it was originally developed by


Cleve Moler in the 1970’s.
 MATLAB is a programming language that provides a numerical computing
environment and a suite of tools for computation, visualization, and more.
 MATLAB is a mathematical and graphical software package that has
numerical, graphical, and programming capabilities.
 It has built-in functions to do many operations, and also toolboxes that can be
added to augment these functions
 A command interface created for interactive management plus a simple
integration of particular functions, programs, and libraries supports the
operation of MATLAB.
 MATLAB is an interpreter language and its commands statements are
translated into machine code one by one by the MATLAB’s interpreter. In
comparison, a compiled programming language like C has a program
translated
15-Mar-21 as a whole into machine code by the compiler.
3

Introduction to MATLAB Cont`d

Advantages of Using MATLAB


i. MATLAB has an excellent documentation
ii. Many toolkits are available which extend MATLAB’s functionality
iii. MATLAB is equipped with an editor with debugging functionality, which
makes the writing and error analysis of large programs very easy.
iv. MATLAB’s matrix manipulation algorithms (esp. for sparse matrices) are
state of the art
v. MATLAB interacts with a special toolbox, Simulink, which is a tool for
constructing simulation programs based on a graphical interface in a way
similar to block diagrams.

Disadvantages of Using MATLAB


i. The scripting system of MATLAB is somewhat primitive
ii. For complex tasks (especially ones which require for loops), MATLAB
can sometimes be slower than C or C++
iii. MATLAB is a commercial software; meaning that it is not free (it is
15-Mar-21
expensive!) 4

2
15/03/2021

Introduction to MATLAB Cont`d

MATLAB User Interface


The typical window interface of a MATLAB software shown to a MATLAB user
when started is illustrated in Fig. 1

Fig. 1: The default MATLAB desktop


The MATLAB desktop comprises the Title bar, Menu bar, Desktop toolbar,
Command
15-Mar-21 window, Command history, Current directory, and Workspace panels.
5

Introduction to MATLAB Cont`d

i. Title Bar: The title bar contains the program’s name with year and logo as well as the
window control buttons. It is situated on the top of the main MATLAB window.
ii. Menu Bar: The menu bar is underneath the title bar. It has commands for opening,
closing files, preferences, open, copy, paste etc.
iii. Desktop Toolbar: The desktop toolbar is placed underneath the menu bar. It contains
many items such as, new file, new script, open, import data, help etc.
iv. Command Window: It is the most important part of the MATLAB main desktop. It is
the window where input and output appears, the user can enter commands and obtain
results. Each new line starts with the symbol “>>” called the command prompt.
v. Command History: The command history window contains the history of the
commands entered in the command window. It begins on each new session with the
starting date and time. Thus, each session history is separated by dates.
vi. Current Folder: On the top of the window there is box containing the location of the
current directory. File names appear on the left column, file types on the middle and
last date of modification on the right column.
vii. Workspace: This window displays the loaded variables of the current MATLAB
session; these are variables you have created and are currently loaded on the memory. It
displays their name, their size, i.e their dimensions, the number of bytes they take on
memory
15-Mar-21 and their class, that is the type of variable.
6

3
15/03/2021

Introduction to MATLAB Cont`d


Saving and Loading Files in MATLAB
 It is necessary to declare a current directory before saving, loading a file, or run an
m-file. By default, the MATLAB current directory will be .../MATLAB/work.
 The current directory can be changed by either using the toolbar at the left-hand
side of the screen, or entering the path in the toolbar at the top.
 The MATLAB first look into the current directory for a function you try to call.
To save file, there are many ways to save files in MATLAB.
 save - saves data to files, *.mat by default
 uisave - includes user interface
 hgsave - saves figures to files, *.fig by default
 diary('filename') - saves all the text input in the command window to a text
file. The files are saved in the current directory
There are many ways to load files into the workspace.
 Use the "file" menu.
To open a .m file click "open" icon, or type
>> open filename.ext
Also, to import data from a data file, select "import data..." and follow the wizard’s
 An 15-Mar-21
alternative way to load a saved .mat file (within a function) is to type:
>> load filename.ext 7

Introduction to MATLAB Cont`d

File Naming Constraints

Files can be name whatever as may wish (usually simpler is better though), with a
few exceptions:

 MATLAB for Windows retains the file naming constraints set by DOS. The
following characters cannot be used in filenames:
"/:*<>|?
 You're not allowed to use the name of a reserved word as the name of a file.
For example, while.m is not a valid file name because while is one of
MATLAB's reserved words.

 When declare an m-file function, the m-file must be the same name as the
function or MATLAB will not be able to run it. For example, if you declare a
function called 'factorial':
function Y = factorial(X)
It must be saved as "factorial.m" in order to use it
15-Mar-21
8

4
15/03/2021

Introduction to MATLAB Cont`d

Starting With MATLAB


There are two (2) ways in which MATLAB can be used; these include:
1) Using the command window and
2) Using an m-file
(1) Using the Command Window
 MATLAB commands or statements can be entered into the command window.
Once the statement has been entered, the <return> key is pressed to execute the
command.
 Example, the addition of numbers 1, 3, and 8 can be executed in the command
window as shown in Fig 2. MATLAB displays the command prompt (>>) to
indicate that it is ready to receive instructions.

Fig. 2: Statement issued in the


command window for performing an
addition task

15-Mar-21
9

Introduction to MATLAB Cont`d

(2) Using an m-file


 M-files are ordinary text files containing MATLAB commands. They are created or
modified using any text editor or word processor that capable of saving files as
plain ASCII text.
 An m-file contains lines of code entered into text editor and saved with the “.m” file
extension. For complicated problems, the simple editing tools provided by the
Command Window is insufficient. A better approach is to create an m-file.
 There are 3 types of m-files namely; (i) Script m-file, (ii) Function m-file and (iii)
Class m-file.
(i) Script m-file:
An m-file is by default a script m-file. A script m-file literally contains a list of
MATLAB commands without any argument [a reference or value that is passed to
a function, procedure, subroutine, command, or program]. Suppose “addition.m”
is a script m-file saved in the current directory, then at the command prompt in the
command window, one may type the following command in order to invoke this
script m-file (see Fig. 3.2):
>> addition
15-Mar-21
10

5
15/03/2021

Introduction to MATLAB Cont`d

Note that in Fig. 3.1, the semicolons on


the 1st, 2nd, and 3rd lines suppress
MATLAB from printing the result of the
commands. Also note that the 4th line of
Fig. 3.1 does not have a semicolon which
makes its result to be printed on screen as
shown in Fig. 3.2
Fig. 3.1: A script m-file saved with the file
name “addition.m” which contains the
code for adding the numbers 1, 2, and 8

Fig. 3.2: Invoking the code in the saved


script m-file. Note that the file name of the
script m-file in this case is “addition.m”

15-Mar-21
11

Introduction to MATLAB Cont`d


(ii) Function m-file:
 A function m-file is a file in which a function is defined. The first (non-comment)
line of a function m-file takes the form:
function [output args] = function_name(input args)
 Note that the name of the function needs to be the same as the m-file filename
 Example, if addition.m is a function m-file and it is saved in the current folder,
the function can be invoked by typing the following command in the command
window (see Fig 4.2): >>d = addition(1,3,8)

Fig. 4.2 Invoking the code in


the saved function m-file.
Note that the file name of the
function m-file in this case is
“addition.m”
Fig. 4.1 A function m-file which has been
saved with the file name “addition.m” In the above example, variables a=1, b=3, and c=8 are
containing the formula for adding any 3 passed as input arguments to the addition function.
numbers passed as argument to it
15-Mar-21 The values of a, b, and c are used in the function for
computation and the result is returned as d=12. 12

6
15/03/2021

Introduction to MATLAB Cont`d


(iii) Class m-file:
 The class m-file type is usually used for implementing object-oriented
programming in MATLAB. Similar to function m-file, the file name must agree
with the class name.
 The functions defined for objects of a class are called class methods. Assuming
function “add” is a method in class “addition” and an object “numbers” is
created from class “addition”, it is possible to call the method “add” by typing
either numbers(add) or numbers.add.[See Figs. 5.1 and 5.2].

Fig. 5.1 A class m-file


which has been saved
with the file name
“addition.m” contains
the method for adding
any 3 numbers passed
as argument to it

Fig. 5.2 Invoking the code in the saved


class m-file. Note that the file name of the
13
class m-file in this case is “addition.m”

Introduction to MATLAB Cont`d


Rules for Naming Variables in MATLAB
 A variable in MATLAB is a symbol used to hold a value. The rules for naming
variables in MATLAB can be summarised as follows:
i. Variable names in MATLAB can be up to 31 characters long
ii. Variable names in MATLAB must start with a letter. The subsequent
characters can be numbers, letters or underscores (some other characters are
also available). There are many choices which are forbidden as variable names,
some for very obvious reasons (such as a*b which signifies a multiplication of
the variables a and b) and others for more subtle reasons.
iii. Variable names in MATLAB are case sensitive, so that voltage and VOLTAGE
are two different objects.
iv. A MATLAB variable must not contain a space character
v. Variables names should not coincide with a predefined MATLAB command or
with any user-defined subroutines. To check whether a variable name is already
in use, type >> which variable_name in command window

15-Mar-21
14

7
15/03/2021

2.0 MATLAB Operators

Scalar Arithmetic Operators Order of Arithmetic Operator Precedence


 A scalar variable is a variable that  Some operators have precedence over others.
contains a single number.  Mathematical expressions are evaluated
 MATLAB uses the symbols +, -, *, starting from the left, with the exponentiation
/, ^ for addition, subtraction, operation having the highest order of
multiplication, division, and precedence, followed by multiplication and
exponentiation (power) of scalars division with equal precedence, followed by
numbers as illustrated in Table 2.1. addition and subtraction with equal
Table 2.1 Scalar arithmetic operators precedence as illustrated in Table 2.1
Table 2.1 Order of evaluation precedence

15-Mar-21
15

MATLAB Operators Cont`d

Example: The following are computations executed using the command window of MATLAB

Relational Operators Table 2.3 Relational operators in MATLAB

 Conditions in if statements use expressions that


are conceptually, or logically, either true or
false.
 These expressions are called relational
expressions, or sometimes boolean or logical
expressions. Expressions can use both
relational operators, which relate two
expressions
15-Mar-21
of compatible types, and logical
operators, which operate on logical operands. 16

8
15/03/2021

MATLAB Operators Cont`d

 Numerical operands example, 3 < 5 means “3 less than 5,” which is conceptually a true
expression. However, in MATLAB, as in many programming languages, logical true is
represented by the integer 1, and logical false is represented by the integer 0. So, the
expression 3 < 5 actually has the value 1 in MATLAB.
 Example in MATLAB command  MATLAB has a function xor, which is the
window demonstrates the values of exclusive or function. It returns logical true if one
the expressions logical operators (and only one) of the arguments is true. Example:

Next, both arguments are true so the result is false

 Mathematical operations could be


performed on the resulting 1 or 0

Assume that there is a variable x that has been


15-Mar-21
initialized (x=4 or x=7). What would the value of
the expression? 3< x < 5 17

MATLAB Operators
 Table 2.4(a) lists the logical operators in MATLAB. Note that A and B are not considered
purely as matrices but as logical expressions.
 The truth table of these operators is illustrated in Table 2.4(b).
2.4(a) Logical operators Table 2.4 (b): Truth table for logical operators

 Table 2.5 shows the rules for the operators covered so far, in the order of precedence
Table 2.5: Operator precedence rules

15-Mar-21
18

9
15/03/2021

MATLAB Operators Cont`d

Predefined Constants
 Variables are used to store values that can change, or that are not known ahead of time.
 Most languages have the capacity to store constants, which are values that are known ahead
of time, and cannot possibly change.
 MATLAB has several predefined special constants. Examples are pi represents π, while Inf
stands for ∞, other predefined constants are illustrated in Table 2.6.
Inf : means a number so large that MATLAB cannot
Table 2.6 Predefined special constants represent it. Example: typing 5/0 will generates Inf.
 NaN: indicates an undefined numerical result such
as that obtained by typing 0/0.
eps is the smallest number which, when added to 1
by the computer, creates a number greater than 1
[usually indicates the accuracy of computations].
 The symbols i and j denote the imaginary unit, used
to represent complex numbers, such as y = 7 + 2i

Note: The use of these special constants as variable names should be avoided. Although
MATLAB allows the programmer to assign a different value to these constants, it is however
not a15-Mar-21
good practice
19

MATLAB Operators Cont`d

Complex Number Operations


 MATLAB handles complex number algebra automatically. For example, the number
c1 =1 - 2i is entered as follows:
c1 = 1-2i.
or
c1 = complex(1, -2).
 Note that an asterisk is not needed between i or j and a number, although it is required
with a variable, such as
c2 = 5 - i*c1.  Addition, subtraction, multiplication, and
division of complex numbers are easily done
This convention can cause errors if care in MATLAB. For example:
is not taken. For example, the expressions
y = 7/2*i
and
x =7/2i
give two different results which are:
y =(7/2)i = 3.5i
and
x = 7/(2i)= -3.5i
(To divide with complex number, multiply numerator and
15-Mar-21
denominator with complex conjugate of the denominator) 20

10
15/03/2021

MATLAB Operators Cont`d

MATLAB Comment
 Comments are used to document programs and the symbol used for indicating comments
in MATLAB is the percent (%) symbol. Hence, MATLAB ignores everything on the right-
hand side of the % symbol as they are treated as comments.
 Comments are categorized into Two
(i) Single line comments: This category of comment spans only one line. MATLAB ignores
everything to the right of the “%” symbol but executes everything to the left of it. For
example
x = 1+2 % addition of numbers

(ii) Multiline comments: This category of comment spans more than one line. This is
accomplished by placing the comment statements in between the symbol pair “%{” and
“%}”. For example
x = 1+2;
y = 1-2;
%{
this program computes
the addition and subtraction
of two numbers
15-Mar-21
%} 21

MATLAB Operators Cont`d

Controlling Input and Output


 MATLAB provides commands for obtaining input from the user and for formatting the
output.
 The simplest input function in MATLAB is called input. The input function is used in an
assignment statement.
 The disp function (“display”) is used to display the result of an expression or a string
without assigning any value to the default variable ans. For examples:

Table 2.7: Input/output


commands

15-Mar-21
22

11
15/03/2021

MATLAB Operators Cont`d


Formatting Command
 The format command controls how numbers appear on the screen. Table 2.8 gives the
variants of this command.
 MATLAB uses many significant figures in its calculations. The default MATLAB display
format is the short format, which uses four decimal digits.
 You can display more by typing format long, which gives 16 digits. To return to the default
mode, type format short.
 You can force the output to be in scientific notation by typing format short e, or format
long e, where e stands for the number 10. Thus the output 6.3792e+03 stands for the
number 6.3792 x103. The output 6.3792e-03 stands for 6.3792 x10-3
Table 2.8 Formatting command

15-Mar-21
23

MATLAB Operators Cont`d

Formatting Specifiers
 The “format” command is convenient for simple programs, but MATLAB provides a far more
sophisticated way for printing information by means of a function borrowed from the
languages C and C++, called “fprintf ”.
 The “fprintf ” stands for “formatted printing to a file” and it requires at least one argument. It
allow writing of information to the screen for the user to see.
 Its first argument is a format string, which is a string that specifies the way in which printing
is to be done (spacing, number of decimal places etc).
 In the format string, the format of each value that is to be printed is specified individually. For
example, one value may be printed with four decimal places and another with fifteen.
 Additionally, any text that is to be printed along with the values is included in the format
string.
 Following the format string there are typically additional input arguments to fprintf. These are
the values that are to be printed and they must appear as arguments in the order that they are
to be printed. For example:

15-Mar-21
24

12
15/03/2021

MATLAB Operators Cont`d

 In the earlier example, the %d, %.2f, and %5.2f are known as conversion characters.
 The percent symbol, “%”, and the characters immediately after indicate to MATLAB that the
value of one argument after the format string, is to be printed in a specific format.
 The meaning of the d in %d, is "If the value is an integer, print it without a decimal
point; otherwise print it in scientific notation."
 The f in %.2f is a format specifier, specifying the format in which an object is to be
printed; i.e., “print using fixed-point notation”
 The 5 in the format %5.2f means “print using at least five spaces.”
 \n, which means "go to a new line"

Table 2.9: Additional format


specifiers and their meanings

15-Mar-21
25

MATLAB Operators Cont`d

MATLAB Built-in Mathematical Functions


 MATLAB has many built-in functions, including trigonometric, logarithmic, and hyperbolic
functions, as well as functions for processing arrays. Some common mathematical functions
are summarised in Table 2.10.
Table 2.10 Mathematical functions

15-Mar-21
26

13
15/03/2021

3.0 MATLAB Data Types

Data Types in MATLAB


 Computers operate on bits, but humans think in terms of numbers, words, and other types of
data. Like any good language, MATLAB organizes bits into convenient data types.
 A MATLAB programmer need not to be concerned with the types of numbers used in a
calculation. The benefit of selecting an appropriate data type for a variable is to save
memory space because types with narrower ranges can be stored in fewer bytes.
 To determine the data type of a MATLAB variable, the function “class” is used.
For example:  MATLAB data types are classified as
(i) Numeric Data Type
>> x = 14; (ii) String Data Type
(iii) Cell Data Type
>> class(x)
(iv) Struct Data Type
ans =
double (I) Numeric Data Type
 The default data type used by MATLAB to store a number is
“double” which is so versatile that its capable of handling almost any
numerical problems in engineering and science applications.
 A comprehensive list of MATLAB numeric data type is shown in
15-Mar-21
Table 3.1.
27

MATLAB Data Types Cont`d

Table 3.1 Numeric data types and their range  Each of these functions takes an array as an
of values input argument and returns either true or false.
The name of the function reveals its meaning:
isinteger(x) returns true if and only if x is of
one of the integer types.
 The data type of a variable can be converted to
another data type. For example

Note: If a conversion
function is given a value
outside its range, it will
 The word int embedded in all except two, the return the value that lies at
names means “integer”; a leading “u” means the closest end of its range.
unsigned, so uint means “unsigned integer”. For example:

 MATLAB provides a set of functions that


allow the user to check for a specific type.
The name of each function begins with “is”.
Examples include isinteger, isfloat, issingle,
15-Mar-21
isnumeric, and ischar.
28

14
15/03/2021

MATLAB Data Types Cont`d

(II) String Data Type


 A string is a row vector of numbers of type char, each number being a code that represents
one character.
A string is defined with the use of the ‘ ’ operator. The general syntax is:
the_string = ’somecharacters’
 Each individual element of a string
For example:
>> t = ‘a string’ can be accessed using an indexing
t= scheme.
a string For example
 The sequence of numbers that encode a string
>> course = ‘ELE 562’;
is stored as a standard row vector. >> course(1)
 The length of the vector is equal to the ans =
number of characters in it. For example: E
>> course (1:3)
ans =
ELE
>> course (5:7)
ans =
562
15-Mar-21
29

MATLAB Data Types Cont`d


 One of the schemes used for encoding characters as numbers is shown in Table 3.2. This
encoding scheme is called ASCII (American Standard Code for Information Interchange)
Table 3.2: ASCII code
Dec Char Dec Char Dec Char Dec Char Dec Char Dec Char Dec Char
0 NULL 20 DC4 40 ( 60 < 80 P 100 d 120 x
1 SOH 21 NAK 41 ) 61 = 81 Q 101 e 121 y
2 STX 22 SYN 42 * 62 > 82 R 102 f 122 z
3 ETX 23 ETB 43 + 63 ? 83 S 103 g 123 {
4 EOT 24 CAN 44 , 64 @ 84 T 104 h 124 |
5 ENQ 25 EM 45 - 65 A 85 U 105 i 125 }
6 ACK 26 SUB 46 . 66 B 86 V 106 j 126 ~
7 BEL 27 ESC 47 / 67 C 87 W 107 k 127 DEL
8 BS 28 FS 48 0 68 D 88 X 108 l
9 HT 29 GS 49 1 69 E 89 Y 109 m
10 LF 30 RS 50 2 70 F 90 Z 110 n
11 VT 31 US 51 3 71 G 91 [ 111 o
12 FF 32 52 4 72 H 92 \ 112 p
13 CR 33 ! 53 5 73 I 93 ] 113 q
14 SO 34 " 54 6 74 J 94 ^ 114 r
15 SI 35 # 55 7 75 K 95 _ 115 s
16 DLE 36 $ 56 8 76 L 96 ` 116 t
17 DC1 37 % 57 9 77 M 97 a 117 u
18 DC2 38 & 58 : 78 N 98 b 118 v
19 DC3 39 ' 59 ; 79 O 99 c 119 w
15-Mar-21
Note that spaces and punctuation marks are all part of the string, and each one is encoded with its own number.
30

15
15/03/2021

MATLAB Data Types Cont`d

 The numeric value of a character can be


obtained by using a conversion function.
For example
Table 3.3: Illustration of Some string functions
>> course = ‘ELE 562’;
>>double(course) Function Description
ans = char converts type to char
69 76 69 32 53 54 50 findstr finds the positions of a substring in a string
ischar returns 1 if argument is a character array and 0
otherwise
 Numbers can also be isletter finds letters in string
converted to characters. isspace finds spaces, newlines, and tabs in string
For example: isstrprop finds characters of specified type in string
num2str converts number to string
>> course = 'ELE 562' length determines the number of letters in string
course = lower converts string to lower case
ELE 562 sprintf writes formatted data to string
>> double(course) strcmp compares strings
ans = strcmpi like strcmp but independent of case
69 76 69 32 53 54 50
>> char(course)
strmatch search array for rows that begin with specified string
ans = strncmp like strcmp but compares only first n characters
ELE 562 strncmpi like strncmp but independent of case
str2num converts string to number
15-Mar-21 upper converts string to upper case
31

MATLAB Data Types Cont`d

(III) Cell Data Type


 Cell arrays can hold multiple data types. It is possible for example to have a string, various
types of matrices as well as a cell array inside a cell array.
 Cell arrays are constructed with the use of the curly brackets {}.
For example, if it is desired to construct a 2 x 2 cell array whose cell contains the student’s
name, matric number, courses, and scores in test and exam. The cell array could be as follows:

ADE 13/30GC1000 The cell may be constructed using the MATLAB statement:
ELE447 Student = {‘ADE’, ‘13/30GC1000’; {‘ELE447’;’ELE562’},
25 45
ELE562 22 50 [25,45; 22,50]}
 

 To display cell array Student,


the celldisp function can be
used.
15-Mar-21
Note that space or comma defines the next column and semicolon defines the next row. 32

16
15/03/2021

MATLAB Data Types Cont`d

 To access a specific element of any data type inside a cell, an operator is placed immediately
after curly brackets e.g. if the cell element is an array or a string, curly brackets {} are used; if
the cell element is in another cell, round brackets () are used.

For example

Assigning Data to Cells


Data can be assigned to the cells by
using either
(i) cell indexing or
(ii) content indexing

15-Mar-21
33

MATLAB Data Types Cont`d


(i) Cell Indexing: on the left side of the cell assignment statement, the cell subscripts are
enclosed in round brackets, while on the right side, cell contents are enclosed in curly
brackets.
For example, consider the cell array: The cells can be assigned data values as follows:
ADE 13/30GC1000 Student(1,1) = {'ADE'}
Student(1,2) = {'13/30GC1000'}
ELE447 25 45 Student(2,1) = {'ELE447;ELE562'}
ELE562 22 50 Student(2,2) = {['25,45;22,50']}
 
Table 3.4: Illustration of some cell functions and
(ii) Content Indexing: on the left side of the their description
cell assignment statement, the cell Function Description
subscripts are enclosed in curly brackets, cell create an array of type cell
then specify the cell contents on the right celldisp show all the objects pointed at by a cell
side of the assignment operator. array
cellfun apply a function to all the objects pointed
The cells can be assigned data values
at by a cell array
as follows:
cellplot show a graphical depiction of the contents
Student{1,1} = 'ADE' of a cell array
Student{1,2} = '13/30GC1000'
cell2struct convert a cell array into a struct array
Student{2,1} = ['ELE447;ELE562']
Student{2,2} = ['25,45;22,50'] deal copy a value into output arguments
15-Mar-21 iscell returns true if argument is of type cell
num2cell convert a numeric array into a cell array34

17
15/03/2021

MATLAB Data Types Cont`d


(IV) Struct Data Type
An array consists of a collection of elements having the same elementary data type. The
array is said to be homogeneous with regard to the types of its element. It is not possible,
therefore, to have a matrix whose first element is of type int16 and whose second element is
of type char. A struct provides a way of having multiple data types within a single variable.
A struct differs from an array in the following respects
(i) The elements of an array always have the same data type but a struct can have
elements belonging to different data types.
(ii) Each element of an array has a numerical index but the index of an element of a
struct is usually a user-defined name.
Structs use the dot notation (.) to specify and to access the fields.
A struct can be created in two ways
(i) By using assignment statements (ii) By using struct functions

Using Assignment Statement


Supposing it is desired to create a struct that contains the following types of student data:
*Student name
*Student matric number
*Student email
15-Mar-21
*Student age 35

MATLAB Data Types Cont`d

This can be accomplished as follows The data of the second student can be viewed as follows:
>>student(2)
name: ‘CHIKE’
matric_no : ‘13/30GC1001’
email :
[email protected]
age: 23
 The elements of the struct student can
be viewed by typing the command: Using Struct Function
>>student As an alternative to assignment statement, structs can
>>student be constructed using the struct function which
name: ‘ADE’ preallocates a struct array. To build a struct array
matric_no : ‘13/30GC1000’
email : ‘[email protected]’ named str_array, the syntax is:
age: 21 str_array = struct(‘field1’,’values1’, ‘field2’,
‘values2’, ‘field3’, ‘values3’, . . .). For example:
 To add a second student to the database,
a subscript is enclosed in round brackets >>student = struct(‘name’,‘ADE’, ‘matric_no’ ,
‘13/30GC1000’,‘email’, ‘[email protected]’, ‘age’, 21)
after the struct’s name: student=
student(2).name = ‘CHIKE’; name: ‘ADE’
student(2).matric_no = ‘13/30GC1001’; matric_no : ‘13/30GC1000’
student(2).email = ‘[email protected]’; email : ‘[email protected]
student(2).age
15-Mar-21 = 23; age: 21
36

18
15/03/2021

MATLAB Data Types Cont`d

 To delete a field from every struct in the array , use the rmfield function.
The syntax is:
array_name = rmfield(array_name, ‘field’)
 Assuming the email field is to be removed from the struct student, it can be achieved by
typing : student = rmfield(student, ‘email’)
For example: Table 3.5: Some struct functions
>> student = rmfield(student, Function Description
‘email’) names = Returns the field names associated
student=
fieldnames(student) with the struct array student
name: ‘ADE’
matric_no : ‘13/30GC1000’ isfield(student, Returns 1 if ‘this_field’ is the name
age: 21 ‘this_field’) of a field in the struct array student
and 0 otherwise.
isstruct(student) Returns 1 if the array student is a
struct array and 0 otherwise.
Table 3.5 illustrates other functions student = Removes the field ‘this_field’ from
that can be used with struct student rmfield(student, the struct array student
and their descriptions. Student is ‘this_field’)
variable name. student = struct(‘ Creates a struct array student with
field1’,’values1’, ... the fields ‘field1’, ‘field2’, . . .
15-Mar-21 ‘field2’, ‘value2’, having the values ‘value1’,
‘field3’, ‘value3’, . . .) ‘value2’, ... 37

MATLAB Data Types Cont`d

Dimension of MATLAB Variables


 By default, all variables in MATLAB are treated as matrices (i.e., array of elements). Based
on dimension, MATLAB variables can take any of the following forms:
(I) Scalar (i.e., 1 x 1 matrix)
(II) Vector (i.e., n x 1 or 1 x n matrix)
(III) Matrix (n x m matrix; where n and m may or may not be equal)
(IV) Multi-dimensional array (e.g., n x m x q array)
(I) Scalar: A scalar variable contains a single For example
element and in MATLAB, it is treated as a 1x1 >>A = 10
matrix. It is entered without any brackets. A=
10

(II) Vector: A vector in MATLAB is simply a matrix with exactly one column or exactly one
row. A variable with exactly one row is called a row vector while a variable containing exactly
one column is called a column vector.
 Vectors in MATLAB are enclosed in square brackets.
Consider the following vectors: A  1 3 5 1 
 
B  3
5
 
To enter row vector A and column vector B in MATLAB, one may type:
A = [1,3,5]
15-Mar-21
or A = [1 3 5] and
B = [1;3;5] 38

19
15/03/2021

MATLAB Data Types Cont`d


 The colon “:" is one of the most useful operators in >>A = 2:5
MATLAB. One of its usages is in the construction of A=
row vectors with regularly spaced values. For example: 234 5

 If the spacing between the elements is not 1, then the spacing has to be specify. For
example, if the spacing is 0.5 then, the previous expression is modified as follows
>>A = 2:0.5:5
A=
2 2.5 3 3.5 4 4.5 5

(III) Matrix: Scalars and vectors are regarded as special cases of matrices. A matrix is entered
by rows, with entries/elements in a row separated by spaces or commas, and the rows
separated by semicolons. The entire matrix is enclosed in square brackets.
Assuming a matrix A is a 3 by 2 matrix written as:
In command window:
1 2  In MATLAB, matrix A is entered as:
  >>A = [1,2;3,4;5,6]
A   3 4  A = [1,2,;3,4;5,6] A= 1 2
5 6 3 4
  5 6
15-Mar-21
39

MATLAB Data Types Cont`d

(IV) Multidimensional Array: An array having more than two


dimensions is called a multidimensional array in the MATLAB
application.
 Multidimensional arrays in MATLAB are an extension of the
normal two-dimensional matrix.

 Multidimensional arrays use additional


subscripts for indexing. For example a three-
dimensional array., uses three subscripts:
•The first references array dimension 1, the row.
•The second references dimension 2, the column.
•The third references dimension 3.
>>A(:,:,2) = [1 0 4; 3 5 6; 9 8 7]
 The illustration uses the concept of a For example: A(:,:,1) =
page to represent dimensions 3. 5 7 8
>>A = [5 7 8; 0 1 9; 4 3 6]
0 1 9
A=
 A multidimensional array can be created 4 3 6
from 2-D array by extending it. 5 7 8 A(:,:,2) =
 Create a 2-D array A and extend A to a 3- 0 1 9 1 0 4
D array using indexed assignment: 4 3 6 3 5 6
15-Mar-21 9 8 7
40

20
15/03/2021

4.0 Addressing Matrices in MATLAB


Matrix Indices
 Matrix indices are the row and column numbers of an element in a matrix and are used to
keep track of the matrix’s elements. For example, the notation V(5) refers to the fifth
element in the vector V, and A(2,3) refers to the element in row 2, column 3 in the matrix A.
 Note that: (i) the row number is always listed first!
(ii) indices always start at 1 and NOT at 0

 To selects individual elements, rows, columns, or “submatrix” of a matrix, the colon


operator (:) is used. Some example in which the colon operator has been put to use are as
follows:

• V(:) represents all the row or column elements of the vector V.


• V(2:5) represents the second through fifth elements; that is V(2), V(3), V(4), V(5).
• A(:,3) denotes all the elements in the third column of the matrix A.
• A(3,:) denotes all the elements in the third row of A.
• A(:,2:5) denotes all the elements in the second through fifth columns of A.
• A(2:3,1:3) denotes all the elements in the second and third rows that are also in the first
through third columns.
• V = A(:) creates a vector V consisting of all the columns of A stacked from first to last.
• A(end,:) denotes the last row in A, and A(:,end) denotes the last column.
15-Mar-21
41

Addressing Matrices in MATLAB Cont`d

Assuming a matrix A is given as follows


>>A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13]
1 2 7 11 A= 1 2 7 11
  3 4 9 12
A  3 4 9 12  which is written in MATLAB as:
5 5 6 10 13
 6 10 13 
>>a = A(3,2)
To get the element at row 3, column 2, one may type: a =
6
 To change the element at row 3, column 1 >>A(3,1) = 20
from its current value 5 to 20, one may A= 1 2 7 11
type: >>A(3,1) = 20 3 4 9 12
20 6 10 13
 To get submatrix B which is equal
to rows 2 and 3, and columns 2, 3,
and 4 of matrix A, one can type:  One may permute columns (or rows) simply by typing
>> B = A( : , [4,2,1,3] )
>> B = A([2 3],[2 3 4])
B= >> B = A( : , [4, 2, 1, 3] )
4 9 12 B=
6 10 13 11 2 1 7
12 4 3 9
Equivalent expressions for getting submatrix B include 13 6 20 10
>>B = A( 2:3 , 2:4 )
>>B = A( 2:3 , 2:end) 42

21
15/03/2021

Addressing Matrices in MATLAB Cont`d

 Consider the following matrices  To delete the second row of matrix A, type
0 0 0 0 0 0 >>A([2],:)=[]
  1 2 7 11
 
0 0 0 0 0 0 A  3 4 9 12  >>A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13]
P
0 0 0 0 0 0 5 6 10 13  >> A([2], :) = []
  
0 0 0 0 0 0  A=

1 2 7 11
 It is possible to assign new values to 5 6 10 13
part/entire block in matrix P as follows
 Similarly, to delete the third column of matrix
>> P = [0,0,0,0,0,0;0,0,0,0,0,0 A, type : >>A(:,[3]) = []
0,0,0,0,0,0;0,0,0,0,0,0];
>> A = [1, 2, 7, 11; 3, 4, 9, 12; 5, 6, 10, 13];  To delete variable A from memory, one may
>> P(2:4,2:5) = A type >>clear A
P=
0 0 0 0 0 0
0 1 2 7 11 0  To transpose a matrix and creating complex
0 3 4 9 12 0 conjugates, the operator “ ‘ ” is used.
0 5 6 10 13 0
 To transpose a matrix without creating complex
 Assuming matrix A is as conjugates, the operator “ .‘ ” is used.
Assuming matrix A is:
1 2 7 11
 
A  15-Mar-21
3 4 9 12  1  j 2  3 j 
A   
5 6 10 13 
 3 14 j  43

Addressing Matrices in MATLAB Cont`d


The transpose operators can be applied to matrix A as follows:
>>A=[1-j,2+3j; 3,1+4j] >>A=[1-j,2+3j; 3,1+4j];
A= A .’
1.0000 - 1.0000i 2.0000 + 3.0000i ans =
3.0000 1.0000 + 4.0000i 1.0000 - 1.0000i 3.0000
> A' 2.0000 + 3.0000i 1.0000 + 4.0000i
ans =
1.0000 + 1.0000i 3.0000
2.0000 - 3.0000i 1.0000 - 4.0000i Table 4.1: Some array functions and their description
Function Description
find(x) Computes an array containing the indices of the nonzero elements of the array x.
length(A) Computes the number of elements of A if A is a vector or the largest value of m or n if A is an m x n matrix.
linspace(a,b,n) Creates a row vector of n regularly spaced values between a and b.
logspace(a,b,n) Creates a row vector of n logarithmically spaced values between a and b.
max(A) Returns algebraically largest element in A if A is a vector. Returns a row vector with the largest elements in each
column if A is a matrix. If any of the elements are complex, max(A) returns the elements that have the largest
magnitude
[x,k] = max(A) Similar to max(A) but stores the maximum values in the row vector x and their indices in the row vector k.
min(A) Same as max(A) but returns minimum values.
[x,k] = min(A) Same as [x,k] = max(A) but returns minimum values.
norm(A) Computes a vector’s geometric length
size(A) Returns a row vector [m n] containing the sizes of the m x n array A.
sort(A) Sorts each column of the array A in ascending order and returns an array the same size as A.
mean(A) Mean of elements of vector A
sum(A) 15-Mar-21 Sums the elements in each column of the array A and returns a row vector containing the sums.
std(A) Standard deviation of elements of vector A 44

22
15/03/2021

Addressing Matrices in MATLAB Cont`d


Constructing Special Matrices
 MATLAB commands can be used to construct special matrices. Some of these
commands are illustrated in Table 4.2
Table 4.2: Functions for constructing special (i) Element-by-element operation: This includes
matrices array addition, array subtraction, element by
Function Description element multiplication, etc. as summarised in
eye(n) Creates an n x n identity Table 16.
matrix.
Table 4.3: Element-by-element array operation
eye(size(A)) Creates an identity matrix
the same size as the matrix A. Symbol Operation Form Example
ones(n) Creates an n x n matrix of 1s. + Scalar-array A+b [2, 5] + 4 = [6, 9]
ones(m,n) Creates an m x n array of 1s addition
ones(size(A)) Creates an array of 1s the - Scalar-array A-b [10, 7] - 6 = [4, 1]
same size as the array A. subtraction
zeros(n) Creates an n x n matrix of 0s + Array addition A+B [2, 5] + [10, 7] = [12, 12]
zeros(m,n) Creates an m x n array of 0s. - Array A-B [2, 5] + [10, 7] = [-8, -2]
subtraction
zeros(size(A)) Creates an array of 0s the
.* Array A .* B [2, 5] .* [10, 7] = [20, 35]
same size as the array A.
multiplication
Array Arithmetic Operation ./ Array right A ./ B [2, 5] ./ [10, 7] = [2/10, 5/7]
division
MATLAB has two forms of arithmetic Array left A .\ B [2, 5] .\ [10, 7] = [2\10, 5\7]
.\
operations for arrays namely: division
(i) Element-by-element operation
15-Mar-21 .^ Array A .^ B [2, 5] .^ 3 = [2 ^ 3, 5^3]
(ii) Matrix operation exponentiation 45

Addressing Matrices in MATLAB Cont`d


 Array addition and subtraction require that both arrays be of the same size. The
only exception to this rule in MATLAB occurs when we add or subtract a scalar to
or from an array.
 When two arrays have identical sizes, their sum or difference has the same size and
is obtained by adding or subtracting their corresponding elements, e.g., if
1 2  and B   5 9  Then A  B  1 2    5 9    6 11  >>A = [1,2;3,4];
>>B = [5,9;10,13];
A    10 13   3 4  10 13  13 17 
3 4          >>A + B
ans =
 MATLAB defines element-by-element multiplication 6 11
13 17
only for arrays that are of the same sizes. >>A = [1,2;3,4];
>>B = [5,9;10,13];
For example: >>A .* B
ans =
5 18
30 52

Work Example
The voltage, v, across a resistor is given as (Ohm’s Law), v = Ri , where i is the current and R the
resistance. The power dissipated in resistor R is given by the expression
P = Ri2
If R = 10 Ohms and the current is increased from 0 to 10 A with a step of 2 A, write a MATLAB
15-Mar-21
program to generate a table of current, voltage and power dissipation. 46

23
15/03/2021

Addressing Matrices in MATLAB Cont`d


Work Example
The voltage, v, across a resistor is given as (Ohm’s Law), v = Ri , where i is the current and R the resistance. The power
dissipated in resistor R is given by the expression
P = Ri2
If R = 10 Ohms and the current is increased from 0 to 10 A with a step of 2A, write a MATLAB program to generate a
table of current, voltage and power dissipation.

Solution
% Voltage and power calculation
R=10; % Resistor value
i = (0:2:10); % Generate current values from 0 A to 10 A in steps
of 2 A
v = i .* R; % array multiplication to obtain voltage
P = (i .^ 2)*R; % power calculation
fprintf('Current:\t')
fprintf('%d \t', i) % display current values
fprintf('\n')
fprintf('Voltage:\t')
fprintf('%d \t', v) % display voltage values
fprintf('\n')
fprintf('Power:\t')
fprintf('%d \t', P) % display power values
fprintf('\n')

The results are displayed as :


Current: 0 2 4 6 8 10
15-Mar-21 Voltage: 0 20 40 60 80 100
Power: 0 40 160 360 640 1000 47

Addressing Matrices in MATLAB Cont`d


(ii) Matrix Operations

Matrix Addition and Subtraction:


 Matrix addition and subtraction are identical to element-by-element addition and
subtraction. The corresponding matrix elements are summed or subtracted.
Matrix Multiplication and Division:
 Matrix multiplication and division are not the same as element-by-element multiplication
and division.
 To multiply matrices A and B, the number of columns in A must equal to the number of
rows in B and the product AB has the same number of rows as A and the same number of
columns as B.
e.g., if 1 2 
  1 2  1 x 5  2 x 7 1 x 9  2 x 6  19 21 
A   3 4  and B   5 9  AB 

3 4
 5 9  
 
  
3 9  7 6   
7 6   3 x 5  4 x 7 3 x 9  4 x 6    43 51 
=
    3 9     
   3 x 5  9 x 7 3 x 9  9 x 6   78 81 
>>A = [1,2;3,4;3,9];
To execute it in MATLAB, one may >>B = [5,9;7,6];
type the following: >>A*B
ans =
19 21
15-Mar-21 43 51
78 81 48

24
15/03/2021

Addressing Matrices in MATLAB Cont`d

 Matrix division can either be the left division operator \ or the right division operator /
The right division A/B, for instance, is algebraically equivalent to A
B B
while the left division A\B is algebraically equivalent to
A
If B * C = A and B is non-singular, the left division, B\A is equivalent to MATLAB
expression
C = inv(B) *A
where inv is the MATLAB function for obtaining the inverse of a matrix.
The right division denoted by A/B is equivalent to the MATLAB expression
C = A *inv(B)

Matrix Exponentiation
Raising a matrix to a power is equivalent to repeatedly multiplying the matrix by itself, for
example, A2 = AA. This process requires the matrix to have the same number of rows as
columns; that is, it must be a square matrix. MATLAB uses the symbol “^” for matrix
exponentiation.

15-Mar-21
To find A2, type A^2
49

5. MATLAB Language Construct

 MATLAB has some program-like constructs. In this course, the control flow constructs are
of particular interest. The control flow constructs can be used to control the running of a
sequence of commands within a program.

THE IF STATEMENT

The if statement’s basic form is


if logical expression
statements
end
 Every if statement must have an accompanying end statement. The end statement marks
the end of the statements that are to be executed if the logical expression is true.
 A space is required between the if and the logical expression, which may be a scalar, a
vector, or a matrix.
For example
if x >= 0
y = sqrt(x)
end
15-Mar-21
50

25
15/03/2021

MATLAB Language Construct Cont`d

THE ELSE STATEMENT


 When more than one action can occur as a result of a decision, we can use the else and
elseif statements along with the if statement.
 The basic structure for the use of the else statement is
if logical expression
For example if x >= 0
statement group 1 y = sqrt(x)
else else
statement group 2 y = exp(x) - 1
end end

When the test, if logical expression, is performed, where the logical expression may be an
array, the test returns a value of true only if all the elements of the logical expression are true!
For example, if we fail to recognize how the test works, the following statements do not
perform the way we might expect.
>> x = [4, -9, 25];
When this program is run, it
if x < 0
gives the result
disp('Some of the elements of x are negative. ')
y=
else
2 0 + 3.000i 5
y = sqrt(x)
end
15-Mar-21
51

MATLAB Language Construct Cont`d

THE ELSEIF STATEMENT


 The general form of the elseif statement is
if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end

 Any of else and elseif statements may be omitted if not required. However, if both are used,
the else statement must come after the elseif statement to take care of all conditions that
might be unaccounted for.
For example
if x >= 5
y = log(x)
elseif x >= 0
y = sqrt(x)
end
Note15-Mar-21
that the elseif statement does not require a separate end statement. 52

26
15/03/2021

MATLAB Language Construct Cont`d

Example
A 3-bit analogue to digital converter, with an analog input x and digital output y, is represented
by the equation:
y=0 x< -2.5 y=4 0.5 ≤ x < 1.5
=1 -2.5 ≤ x < -1.5 =5 1.5 ≤ x < 2.5
=2 -1.5 ≤ x < -0.5 =6 2.5 ≤ x < 3.5
=3 -0.5 ≤ x < 0.5 =7 x≥ 3.5
(a) Write a MATLAB function to convert analog signal x to digital signal y.
(b) Test the program by obtaining the corresponding digital outputs y1, y2 and y3 for analog signal inputs
x1, x2, and x3 when the amplitudes of the inputs are
(i) x1 = -1.25
(ii) x2 = 2.57
(iii) x3 = 6.0
(c) What are the results obtained in part b(i) through b(iii) above

Solution
(a) The following program is written and saved as an m-file with the file name
“analog_to_digital.m”
15-Mar-21
53

MATLAB Language Construct Cont`d

%{
analog_to_digital is a function program for
obtaining the digital value given an input analog
signal. Note that:
Y_dig is the digital number (in integer form)
X_analog is the analog input (in decimal
form)
%} (b) The function “analog_to_digital” is
called using the given analog inputs x1, x2,
function Y_dig = analog_to_digital (X_analog)
and x3 as follows
if X_analog < -2.5
Y_dig = 0; (i) x1 = -1.25
elseif X_analog >= -2.5 & X_analog < -1.5 y1 = analog_to_digital (x1)
Y_dig = 1; (ii) x2 = 2.57
elseif X_analog >= -1.5 & X_analog < -0.5 y2 = analog_to_digital (x2)
Y_dig = 2;
elseif X_analog >= -0.5 & X_analog < 0.5 (iii) x3 = 6.0
Y_dig = 3; y3 = analog_to_digital (x3)
elseif X_analog >= 0.5 & X_analog < 1.5
Y_dig = 4; (c) the results obtained are
elseif X_analog >= 1.5 & X_analog < 2.5
Y_dig = 5;
y1 =
elseif X_analog >= 2.5 & X_analog < 3.5 2
Y_dig = 6; y2 =
else 6
Y_dig = 7;
y3 =
end
Y_dig;15-Mar-21 7
end 54

27
15/03/2021

MATLAB Language Construct Cont`d

LOOPS STATEMENT – FOR LOOPS


 A loop is a structure for repeating a task a number of times. Each repetition of the loop is
called a pass.
 MATLAB uses two types of explicit loops namely
-the for loop: is used when the number of passes is known ahead of time, and
-the while loop: is used when the looping process must terminate when a specified
condition is satisfied and thus the number of passes is not known in advance.
The typical structure of a for loop is: for loop variable = m:s:n
statements
end
The expression m:s:n assigns an initial value of m to the loop variable, which is incremented
by the value s, called the step value or incremental value. The statements are executed once
during each pass, using the current value of the loop variable. The looping continues until the
loop variable exceeds the terminating value n.
For example: for k = 5:10:35
x = k^2
end

The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each
successive
15-Mar-21 pass through the loop increments k by 10 and calculates x until k exceeds 35.

Thus k takes on the values 5, 15, 25, and 35; and x takes on the values 25, 225, 625, and 1225. 55

MATLAB Language Construct Cont`d

Example
 Write a MATLAB program for constructing a 5x5 matrix that has 1s in the first row and first
column, and whose remaining elements are the sum of two elements, the element above and
the element to the left, if the sum is less than 20. Otherwise, the element is the maximum of
those two element values. The following function creates this matrix. The row index is r; the
column index is c.
Solution
A = ones(5); The result obtained after running
for r = 1:5 the program is:
for c = 1:5
if (r > 1) & (c > 1) % reserve r1 & C1 1 1 1 1 1
s = A(r-1,c) + A(r,c-1); 1 2 3 4 5
if s < 20
1 3 6 10 15
A(r,c) = s; % assign s to A indices
1 4 10 10 15
else
A(r,c) = max(A(r-1,c),A(r,c-1));
1 5 15 15 15
end
end
end
end
15-Mar-21
disp(A)
56

28
15/03/2021

MATLAB Language Construct Cont`d

  2  10 4 
Example  
Consider the array A given as A   16  20 49 
 81 64  8 
 
 Write a MATLAB program that constructs an array B such that each element in B is
obtained by computing the square root of a corresponding element in A if the element in A
is not less than 0. If an element in A is less than 0, the corresponding element in B is
obtained by adding 50 to the element in A.
Solution

A = [-2, -10, 4; 16, -20, 49; 81, 64, -8]; The result obtained after
for m = 1:size(A) running the program is:
for n = 1:size(A)
if A(m,n) >= 0 B=
B(m,n) = sqrt(A(m,n));
else 48 40 2
B(m,n) = A(m,n) + 50; 4 30 7
end 9 8 42
end
end 15-Mar-21
disp(B) 57

MATLAB Language Construct Cont`d

WHILE LOOP
 A WHILE loop allows the execution of a group of statements to be repeated as long as a
specified condition is satisfied.
 The general form of the WHILE loop is
while expression 1
statement group 1
end
 When expression 1 is true, statement group 1 is executed. At the end of executing the
statement group 1, the expression 1 is retested. If expression 1 is still true, the statement
group 1 is again executed. This retesting and statement execution continues until
expression 1 is false, then program exits the while loop. The following example illustrates
the use of the while loop. x = 5;
while x < 25
disp(x)
x = 2*x - 1;
end
The results displayed by the disp statement are 5, 9, and 17. The loop variable x is initially
assigned the value 5, and it has this value until the statement x = 2*x - 1 is encountered the
first time. The value then changes to 9. Before each pass through the loop, x is checked to see
whether its value is less than 25. If so, the pass is made. If not, the loop is skipped and the
15-Mar-21
program continues to execute any statements following the end statement. 58

29
15/03/2021

MATLAB Language Construct Cont`d

 For the while loop to function properly, the following two conditions must be satisfied:
1. The loop variable must have a value before the while statement is executed.
2. The loop variable must be changed somehow by the statements enclosed in the while loop.

Example
Write a script to determine the number of terms required for the sum of the series
5k2 - 2k, k = 1, 2, 3, . . . , to exceed 10 000. What is the sum for this many terms?

Solution
Because number of times that the expression 5k2 - 2k is to be evaluated is unknown, a while
loop can be employed. The script file is as follows:

total = 0;
 The result obtained after
k = 0;
running the program is:
while total < 1e+4
k = k + 1;
total = 5*k^2 - 2*k + total; The number of terms is:
end 18
disp('The number of terms is: ') The sum is:
disp(k) 10203
disp('The sum is: ')
15-Mar-21
disp(total) 59

MATLAB Language Construct Cont`d

THE SWITCH STATEMENT


 The switch statement provides an alternative to using the if, elseif, and else commands.
 Anything programmed using switch can also be programmed using if structures. However,
for some applications, programs written based on the switch statement is more readable
than programs written based on the if statement.
The switch syntax is:
switch input expression (scalar or string)
case value1
statement group 1
case value2
statement group 2
.
.
.
otherwise
statement group n
end

The input expression is compared to each case value. If they are the same, then the statements
following that case statement are executed and processing continues with any statements after
15-Mar-21
the end statement. 60

30
15/03/2021

MATLAB Language Construct Cont`d


 If the input expression is a string, then it is equal to the case value if strcmp returns a value
of 1 (true). Only the first matching case is executed.
 If no match occurs, the statements following the otherwise statement are executed.
However, the otherwise statement is optional. If it is absent, execution continues with the
statements following the end statement if no match exists.
 Each case value statement must be on a single line.
Example: Suppose the variable angle has an integer value that represents an angle measured
in degrees from North. The following switch block displays the point on the compass that
corresponds to that angle.
switch angle % angle can be 45, 135, or any other value
case 45
disp('Northeast')
case 135
disp('Southeast')
case 225
disp('Southwest')
case 315
disp('Northwest')
otherwise
15-Mar-21
disp('Direction Unknown')
end 61

MATLAB Language Construct Cont`d


 The switch statement can handle multiple conditions in a single case statement by enclosing
the case value in a cell array. For example, the following switch block displays the
corresponding point on the compass, given the integer angle measured from North.
switch angle
case {0,360}
disp('North')
case {-180,180}
disp('South')
case {-270,90}
disp('East')
case {-90,270}
disp('West')
otherwise
disp('Direction Unknown')
Example
Table 5.1 shows the grouping of the months of the year based on the number of days they have.
Using the information in Table 5.1, write a MATLAB script that displays the number of days in
a month when the answers to the following two questions are supplied by the user of the script:
1. Enter the month
2.15-Mar-21
Is it a leap year (y/n)
62

31
15/03/2021

MATLAB Language Construct Cont`d


Solution
msg = 'Enter the month: ';
month = input(msg, 's');
month_3_letters = month(1:3); % Just use the first three letters
if lower(month_3_letters) == 'feb'
leap = input( 'Is it a leap year (y/n): ', 's');
end
switch lower(month_3_letters)
Table 5.1
case { 'sep', 'apr', 'jun', 'nov'}
days = 30; Months classified by Number of days
case 'feb' number of days in a month
switch lower(leap) February (Common year) 28
case 'y'
days = 29; February (Leap year) 29
otherwise September, April, June, 30
days = 28; November
end January, March, May, 31
otherwise July, August, October,
days = 31; November, December
end
fprintf('%s has %d days ', month, days)
15-Mar-21
63

MATLAB Language Construct Cont`d

The BREAK and CONTINUE Statements


• It is permissible to use an if statement to “jump” out of the loop before the loop variable
reaches its terminating value. The break command, which terminates the loop but does not
stop the entire program, can be used for this purpose. For example,
for k = 1:10
x = 50 - k^2;
if x < 0
break
end
y = sqrt(x);
end
 However, it is possible to write the code to avoid using the break command. This can often
be done with a while loop as explained previously. The break statement stops the execution
of the loop.
 There can be applications where we want not to execute the case producing an error but
continue executing the loop for the remaining passes. We can use the continue statement to
do this.
 The continue statement passes control to the next iteration of the for or while loop in which
it appears, skipping any remaining statements in the body of the loop. In nested loops,
continue
15-Mar-21
passes control to the next iteration of the for or while loop enclosing it.
64

32
15/03/2021

MATLAB Language Construct Cont`d

Example USING AN ARRAY AS A LOOP INDEX


The following code uses a continue  It is permissible to use a matrix expression to
statement to avoid computing the specify the number of passes. In this case the
logarithm of a negative number. loop variable is a vector that is set equal to
x = [10,1000,-10,100]; the successive columns of the matrix
y = NaN*x; expression during each pass.
for k = 1:length(x)  For example:
if x(k) < 0 A = [1,2,3;4,5,6]; 1
continue for v = A
end
4
disp(v)
kvalue(k) = k; end
y(k) = log10(x(k)); 2
end 5
is equivalent to
kvalue
y 3
The results obtained after A = [1,2,3;4,5,6]; 6
running the program are: n = 3;
kvalue = for k = 1:n
1 2 0 4 v = A(:, k)
y= end
15-Mar-21 1 3 NaN 2
65

6.0 Plotting with MATLAB

 One of the outstanding strengths of MATLAB is its capability for graphical visualization of
computational results.
 MATLAB has available simple but powerful graphical functions. MATLAB is thus able to
represent ordinary functions in two-dimensional plots (xy plots) and functions of two
variables in three-dimensional plots with perspective (xyz plots).
Two-dimensional Plot
 The plot function is by far the most commonly used graphical function. A plot can be made
from
o a data set or
o an equation
 A typical xy plot and its various parts is illustrated in Fig. 6.1 and some commands used for
plotting are as follows:
o Plot: The MATLAB basic xy plotting function is written as plot(x,y). With only one
argument, say, plot(y), the plot function will plot the values in the vector y versus their
indices 1, 2, 3, . . . , and so on.
o xlabel: To label the abscissa, the syntax is xlabel(‘text’)
o ylabel: To label the ordinate, the syntax is ylabel(‘text’)
o title: To put a title at the top of the plot, the syntax is title(‘text’)
15-Mar-21
66

33
15/03/2021

Plotting with MATLAB Cont`d

 Note that the order of xlabel, ylabel, and title commands does not matter but they must be placed after
the plot command, either on separate lines using ellipses or on the same line separated by commas.

Data symbol: When data are plotted, each data point is plotted with a data symbol, or point
marker, such as the small circles shown in Fig. 6.1.

The specifier for data markers, line types, and


colours are illustrated in Table 6.1

15-Mar-21
Fig. 6.1 A typical xy plot 67

Plotting with MATLAB Cont`d

Table 6.1 Specifiers for data markers, line types, and colours
Data markers Line types Colors
Dot (.) . Solid line - Black k
Asterisk (*) * Dashed line - - Blue b
Cross (x) x Dash-dotted line -.- Cyan c
Circle (o) o Dotted line .. Green g
Plus sign (+) + Magenta m
Square (□) s Red r
Diamond (◊) d White w
Five-pointed star ( ) p Yellow y

 For example, to plot a graph of y against x using the following specifiers


Data marker = □, line type = - -, and color = yellow
The command is : plot(x,y, ‘s -- y’)

 The plot(x,y) function in MATLAB automatically selects a tick-mark spacing for each axis
and places appropriate tick labels. This feature is called autoscaling

 Axis: the axis command can be used to override the MATLAB selections for the axis limits.
The syntax is axis ([xmin xmax ymin ymax]).
15-Mar-21
68

34
15/03/2021

Plotting with MATLAB Cont`d

Subplot: the subplot command is used to plot several smaller “subplots” in the same figure.
The syntax is subplot(m,n,p).
This command divides the Figure window into an array of rectangular panes with m rows and
n columns. The variable p tells MATLAB to place the output of the plot command following
the subplot command into the pth pane.
 For example, subplot(3,2,5) creates an array of six panes, three panes deep and two panes
across, and directs the next plot to appear in the fifth pane (in the bottom left corner).
For example, the following script file is used to construct Fig. 6.2, which shows the plot of the
functions
y = e-1.2x sin(10x + 5) for 0 ≤ x ≤ 5 and
y = |x3 - 100| for -6 ≤ x ≤6.
x = 0:0.01:5;
y = exp(-1.2*x).*sin(10*x+5);
subplot(1,2,1)
plot(x,y),xlabel('x'),ylabel('y'),a
xis([0 5 -1 1])

x = -6:0.01:6;
y = abs(x.^3-100);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('y'),a Fig. 6.2: Illustration of subplot command
15-Mar-21
xis([-6 6 0 350])
69

Plotting with MATLAB Cont`d

Overlay Plots: Assuming a matrix A has m rows and n columns, the following variants of
the MATLAB basic plotting functions plot(x,y) and plot(y) can be used to create overlay
plots:
 plot(A) plots the columns of A versus their indices and generates n curves.
 plot(x,A) plots the matrix A versus the vector x, where x is either a row vector or a
column vector and A is a matrix with m rows and n columns.
If the length of x is m, then each column of A is plotted versus the vector x.
There will be as many curves as there are columns of A.
If x has length n, then each row of A is plotted versus the vector x. There will be
as many curves as there are rows of A.
 plot(A,x) plots the vector x versus the matrix A.
If the length of x is m, then x is plotted versus the columns of A. There will be
as many curves as there are columns of A.
If the length of x is n, then x is plotted versus the rows of A. There will be as
many curves as there are rows of A.
 plot(A,B) plots the columns of the matrix B versus the columns of the matrix A.
1 7  1 4
   
For example, if matrices A and B are given as 2 8  2 5
A B 
3 9  3 6
15-Mar-21    
4 10  4
  7  70

35
15/03/2021

Plotting with MATLAB Cont`d

 The following script plots the columns


in matrix B against the columns in
matrix A which is illustrated in Fig. 6.3

y
A = [1,7;2,8;3,9;4,10];
B = [1,4;2,5;3,6;4,7];
plot(A,B)
xlabel('x'), ylabel('y')
Fig. 6.3: Plotting matrix B columns against the columns in matrix A

Plots of complex numbers


 If y is complex, plot(y) plots the imaginary parts versus the real parts. Thus plot(y) in this
case is equivalent to plot(real(y),imag(y)).
For example, the script
z = 0.1 + 0.9i;
n = 0:0.01:10;
plot(z.^n), xlabel(‘Real’), ylabel(‘Imaginary’)
this generates a spiral plot shown in Fig. 6.4

15-Mar-21
Fig. 6.4: Plotting a complex number
71

Plotting with MATLAB Cont`d

The hold command


 The hold command creates a plot that needs two
or more plot commands. Assuming that
0 ≤ x ≤ 10
y1= x2
y2= x3
y3=100 + x2
y4= 100 + x3
Suppose it is required to plot y2 versus y1 on the
same plot with y4 versus y3, the following script can
Fig. 6.`5: Demonstration of the “hold” command
be used and the result is illustrated in Fig. 6.5
x = 0:10; • Note that the “gtext” command places a string text in
y1 = x.^2; a figure window at a point specified by the mouse. For
y2 = x.^3; example, the string texts “y2 versus y1” and 'y4 versus
y3 = 100 + x.^2; y3' are placed in Fig. 6.5 when the mouse button is
y4 = 100 + x.^3; clicked within Figure.
plot(y1,y2) • However, when more than one plot command is used,
hold the “gtext” command should not be placed before any
plot(y3,y4) of the plot commands.
gtext('y2
15-Mar-21
versus y1'), gtext('y4 versus y3')
72

36
15/03/2021

Plotting with MATLAB Cont`d

Logarithmic Plots
Logarithmic scales abbreviated as log scales are widely used to
 represent a data set that covers a wide range of values and
 identify certain trends in data.
It is important to remember the following points when using log scales:
i. Negative numbers can not be plotted on a log scale because the logarithm of a
negative number is not defined as a real number.
ii. Number 0 can not be plotted on a log scale because log100 = ln 0 = -∞.
 MATLAB has three commands for generating plots having log scales. The appropriate
command depends on which axis must have a log scale. The commands are:
i. loglog(x,y) : both x and y scales are logarithmic.
ii. semilogx(x,y): the x scale is logarithmic and the y scale is rectilinear.
iii. semilogy(x,y): the y scale is logarithmic and the x scale is rectilinear.

The following script demonstrates the use of the logarithmic plotting functions and Fig. 6.6
illustrates the corresponding graph plotted

15-Mar-21
73

Plotting with MATLAB Cont`d

x1 = 0:0.01:3; y1 = 25*exp(0.5*x1); y2 =
40*(1.7.^x1);
x2 = logspace(-1,1,500); y3 = 15*x2.^(0.37);
subplot(1,2,1),semilogy(x1,y1,x1,y2, '--
'),...
legend ('y = 25e^{0.5x}', 'y = 40(1.7)
^x'),...
xlabel('x'),ylabel('y'),grid,...
subplot(1,2,2),loglog(x2,y3),legend('y =
15x^{0.37}'),...
xlabel('x'),ylabel('y'),grid

Fig. 6.6: Demonstration of the logarithmic plotting functions


Table 6.2: Some other 2D plotting functions
Command Description
bar(x,y) Creates a bar chart of y versus x.
plotyy(x1,y1,x2,y2) Produces a plot with two y axes, y1 on the left and y2 on the right.
polar(theta,r,’type’) Produces a polar plot from the polar coordinates theta and r, using the line
type, data marker, and colours specified in the string type.
stairs(x,y) Produces a stairs plot of y versus x.
stem(x,y) Produces a stem plot of y versus x.
15-Mar-21
74

37
15/03/2021

Plotting with MATLAB Cont`d

 The Table 6.2 contains some other 2D plotting functions. The following script demonstrates
the use of some of these special plotting commands while Fig. 6.7 illustrates the
corresponding graphs generated. stairs(x,y)
x=linspace(0,2*pi,14) title('Stairs plot'), xlabel('x'),
y=sin(x); ylabel('y')
subplot(1,3,1) subplot(1,3,3)
bar(x,y) stem(x,y)
title('Bar plot'), xlabel('x'), title('Stem plot'), xlabel('x'),
ylabel('y') ylabel('y')
subplot(1,3,2)

Fig. 6.7: Demonstration of


the bar, stairs, and stem
plotting commands

15-Mar-21
75

Plotting with MATLAB Cont`d

2
To demonstrate the polar plot, Consider the expression r
1  0.5 cos 
where r denotes distance and θ denotes angle.
 The following script illustrates how the polar plot of the
expression can be realised while Fig. 6.8 shows the
corresponding graph generated.

theta = 0:pi/90:2*pi;
r = 2./(1-0.5*cos(theta));
polar(theta,r),title('Polar plot')

Example
Assuming that the Cartesian coordinates (x,y) can Fig. 6.8: Demonstration of polar plot
be converted to an equivalent polar coordinates
(r,θ) by applying the following expressions:

r  x2  y2   tan 1  y x 
 

Write15-Mar-21
a MATLAB script that converts the cartesian coordinates in Table 6.3 into polar
coordinates and execute the polar plot. 76

38
15/03/2021

Plotting with MATLAB Cont`d

Table 6.3 Cartesian coordinates


x y
1 2
4 3
1 1
4 0
9 1

Solution
points = [1 2; 4 3; 1 1; 4 0; 9 1];
r = sqrt(points(:,1).^2 + points(:,2).^2);
Fig. 6.9: Polar plot
thetha = atan(points(:,2)./points(:,1));
polar(thetha,r)

The result of the plot is illustrated in Fig. 6.9

15-Mar-21
77

Plotting with MATLAB Cont`d

Three-dimensional Plot
MATLAB provides some functions for creating three-dimensional plots which includes
- line plots
- surface plots, and
- contour plots

Line Plot
Lines in three-dimensional space can be plotted with the plot3 function. Its syntax is:
plot3(x,y,z)
For example, consider the following equations
x = e-0.005tsin t
y = e-0.005tcos t
z=t
0 ≤ t ≤ 10π
 The following script can be used to realize the 3D-line
plot of the equations and the corresponding graph
generated is illustrated in Fig. 6.10
Fig. 6.10: Demonstration of 3D-line plot
t = 0:pi/50:10*pi;
plot3(exp(-0.05*t).*sin(t),exp(-0.05*t).*cos(t),t)
xlabel('x'),ylabel('y'),zlabel('z'),grid 78

39
15/03/2021

Plotting with MATLAB Cont`d


Surface Mesh Plot
 The function z = f (x, y) represents a surface when plotted on xyz axes, and the mesh
function provides the means to generate a surface plot.
 Before this function can be used, a grid of points must be generated in the xy plane and then
the function f (x, y) can be evaluated at these points.
The meshgrid function generates the grid and its [X,Y] = meshgrid(-2:0.1:2);
syntax is Z = X.*exp(-((X-Y.^2).^2+Y.^2));
[X,Y] = meshgrid(x,y)
mesh(X,Y,Z),xlabel('x'),ylabel('y'),
Or
[X,Y] = meshgrid(min:spacing:max)
zlabel('z')

After the grid is computed, the surface plot can


be generated with the mesh function. Its syntax is:
mesh(x,y,z)

z
 Consider the expression
 2 
   x  y 2   y 2 
   
z  xe
for -2 ≤ x ≤ 2 and -2 ≤ y ≤ 2
Fig. 6.11 Demonstration of surface mesh plot
The following script can be used to
realize the surface mesh plot of the The surf and surfc functions are similar to mesh and
expression and the corresponding graph meshc except that the former create a shaded surface
15-Mar-21
generated is illustrated in Fig. 6.11 plot.
79

Plotting with MATLAB Cont`d

 Consider the expression


1
z 2
1   x  0. 5 y 
for -5 ≤ x ≤ 5 and 0 ≤ y ≤ 10

 The following script can be used to realize


the surface mesh plot of the expression and
the corresponding graph generated is
illustrated in Fig. 6.12

x=linspace(-5,5,41)';
y=linspace(0,10,41)';
[X,Y]=meshgrid(x,y); Fig. 6.12: Demonstration of surface mesh plot
z=1./(1+(X+0.5*Y).^2);
surf(x,y,z)
xlabel('x'), ylabel('y') ,zlabel('z')

15-Mar-21
80

40
15/03/2021

Plotting with MATLAB Cont`d

Contour Plot
Contour plots provides a means of illustrating regions of constant elevation or depression in a
graph. The syntax is
contour(x,y,z)
This function is used the same way as the mesh function; that is, first use the meshgrid
function to generate the grid and then generate the function values.
Recall that the surface mesh plot for the expression
 2 
   x  y 2   y 2 
   
z  xe
for -2 ≤ x ≤ 2 and -2 ≤ y ≤ 2 was
illustrated in Fig. 6.11. The corresponding
contour plot illustrated in Fig. 6.13 can be
realized using the following script:

[x,y] = meshgrid(-2:0.1:2);
z = x.*exp(-((x-y.^2).^2+y.^2));
contour(x,y,z),xlabel('x'),ylabel('y')

15-Mar-21 Fig. 6.13: Demonstration of contour plot command


81

Plotting with MATLAB Cont`d

Some other 3D plotting functions are illustrated in Table 6.4

Table 6.4 Other 3D plotting functions


Command Description
meshc(x,y,z) Same as mesh but draws a contour plot under the surface.

meshz(x,y,z) Same as mesh but draws a series of vertical reference lines


under the surface.
surfc(x,y,z) Same as surf but draws a contour plot under the surface.

[x,y] = meshgrid(x) Same as [x,y] = meshgrid(x,y).

15-Mar-21
82

41
15/03/2021

7.0 Polynomials

A polynomial has the form:


f  x   a1 x n  a2 x n 1  a3 x n  2    an 1 x 2  an x  an 1

This can be defined in MATLAB as row vector:

[a1, a2, a3, . . . , an-1, an, an+1]

For example, the vector [4,-8,7,-5] represents the polynomial 4x3 - 8x2 +7x - 5.

Polynomial Roots
Polynomial roots can be found with the function:
roots(a)
where a is the array containing the polynomial coefficients.
For example, to obtain the roots of the polynomial x3 +12x2 + 45x + 50 = 0
It can be done in MATLAB as follows:

15-Mar-21
83

Polynomials Cont`d

Polynomial Coefficients
To determine the coefficients of the polynomial whose roots are specified by the
array r, the syntax is:
poly(r)
The result is a row array that contains the polynomial’s coefficients.
For example, to find the polynomial whose roots are 1 and 3  5i
It can be done as follows:

Thus the polynomial is x3 -7x2 + 40x -34 = 0

Polynomial Addition and Subtraction


 To add two polynomials, add the arrays that describe their coefficients.

 If the polynomials are of different degrees, add zeros to the coefficient array of the lower-
degree
15-Mar-21
polynomial.
84

42
15/03/2021

Polynomials Cont`d

For example on addition, consider


f (x) = 9x3 - 5x2 + 3x + 7
whose coefficient array is f = [9,-5,3,7] and
g ( x ) = 6x 2 - x + 2
whose coefficient array is g = [6,-1,2].
The degree of g(x) is 1 less that of f (x). Therefore, to add f (x) and g(x), we append one zero
to g(x). That is, g = [0,6,-1,2]
The two polynomials can then be added as follows:

Polynomial Multiplication and Division

(i) Multiply/Divide Polynomial by Scalar: Multiplying a polynomial by a scalar is straight


forward. For example, the following illustrates how the polynomial f (x) = 9x3 - 5x2 + 3x + 7
can be multiplied by scalar number 5:
15-Mar-21
85

Polynomials Cont`d

 Dividing a polynomial by a scalar is done in a similar way as multiplication except that in


this case, the multiplication operator is replaced by a division operator.

(ii) Multiply/Divide Polynomial by Another Polynomial


To multiply a polynomial by another polynomial, the conv function (conv stands
for “convolve”) can be used.

To divide a polynomial by another polynomial, the deconv function (deconv


stands for “deconvolve”) can be used.
Consider polynomials
f(x) = 9x3 - 5x2 + 3x + 7 and
g(x) = 6x2 – x + 2,
their product is
f(x)g(x) = (9x3 - 5x2 + 3x + 7)(6x2 – x + 2)
15-Mar-21
86

43
15/03/2021

Polynomials Cont`d

also, their division is


9 x3  5 x 2  3 x  7
f  x / g  x   1.5 x  0.5833 with a remainder of -0.5833x +8.1667.
6 x2  x  2
The above multiplication and division can be executed in MATLAB as follows:
>> f = polyval([9,-5,3,7],[0:2:10]);
evaluations = f
evaluations =
7 65 515 1789 4319 8537

OR

>> f = polyval([9,-5,3,7],[0:2:10]);
evaluations = f'
evaluations =
7
65
515
1789
4319
8537
15-Mar-21
87

Polynomials Cont`d

Polynomial Evaluation
 The polyval(a,x) function evaluates a polynomial at specified values of its independent
variable x, which can be a matrix or a vector.
 The polynomial’s coefficient array is denoted by a. The result is the same size as x.

For example, the following illustrates how to evaluate the polynomial f(x) = 9x3 - 5x2
+ 3x + 7 at the points x = 0, 2, 4, . . . , 10

resulting vector f contains six values that correspond to f(0), f(2), f(4), . . . , f(10).
The 15-Mar-21
88

44
15/03/2021

Refer to the MATLAB Application and


Work Examples

15-Mar-21
89

45

You might also like