0% found this document useful (0 votes)
31 views25 pages

ELE 562 Slide

The document provides an overview of the MATLAB software package. It discusses what MATLAB is, its advantages and disadvantages, user interface, saving and loading files, file naming constraints, and how to start using MATLAB either through the command window or m-files. The key aspects covered include MATLAB being a numerical computing environment, its matrix manipulation capabilities, and interacting with Simulink for simulations.

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)
31 views25 pages

ELE 562 Slide

The document provides an overview of the MATLAB software package. It discusses what MATLAB is, its advantages and disadvantages, user interface, saving and loading files, file naming constraints, and how to start using MATLAB either through the command window or m-files. The key aspects covered include MATLAB being a numerical computing environment, its matrix manipulation capabilities, and interacting with Simulink for simulations.

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/ 25

08/02/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: ibrahim.o@unilorin.edu.ng
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

8-Feb-21
2

1
08/02/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
8-Feb-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
8-Feb-21
expensive!) 4

2
08/02/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
8-Feb-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
8-Feb-21 and their class, that is the type of variable.
6

3
08/02/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 8-Feb-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
8-Feb-21
8

4
08/02/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

8-Feb-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
8-Feb-21
10

10

5
08/02/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”

8-Feb-21
11

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
8-Feb-21 The values of a, b, and c are used in the function for
computation and the result is returned as d=12. 12

12

6
08/02/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”

13

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

8-Feb-21
14

14

7
08/02/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

8-Feb-21
15

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
8-Feb-21
of compatible types, and logical
operators, which operate on logical operands. 16

16

8
08/02/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


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

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

8-Feb-21
18

18

9
08/02/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 a8-Feb-21
good practice
19

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
8-Feb-21
denominator with complex conjugate of the denominator) 20

20

10
08/02/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
8-Feb-21
%} 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

8-Feb-21
22

22

11
08/02/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

8-Feb-21
23

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:

8-Feb-21
24

24

12
08/02/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

8-Feb-21
25

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

8-Feb-21
26

26

13
08/02/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
8-Feb-21
Table 3.1.
27

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,
8-Feb-21
isnumeric, and ischar.
28

28

14
08/02/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
8-Feb-21
29

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
8-Feb-21
Note that spaces and punctuation marks are all part of the string, and each one is encoded with its own number.
30

30

15
08/02/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
8-Feb-21 upper converts string to upper case
31

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.
8-Feb-21
Note that space or comma defines the next column and semicolon defines the next row. 32

32

16
08/02/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

8-Feb-21
33

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
8-Feb-21 iscell returns true if argument is of type cell
num2cell convert a numeric array into a cell array34

34

17
08/02/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
8-Feb-21
*Student age 35

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 :
‘chike@unilorin.edu.ng’
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 : ‘ade@unilorin.edu.ng’ 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’, ‘ade@unilorin.edu.ng’, ‘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 = ‘chike@unilorin.edu.ng’; email : ‘ade@unilorin.edu.ng’
student(2).age
8-Feb-21 = 23; age: 21
36

36

18
08/02/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’, . . .
8-Feb-21 ‘field2’, ‘value2’, having the values ‘value1’,
‘field3’, ‘value3’, . . .) ‘value2’, ... 37

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]
8-Feb-21
or A = [1 3 5] and
B = [1;3;5] 38

38

19
08/02/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
8-Feb-21
39

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
8-Feb-21 9 8 7
40

40

20
08/02/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.
8-Feb-21
41

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

42

21
08/02/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  8-Feb-21
3 4 9 12  1  j 2  3 j 
A   
5 6 10 13 
 3 14 j  43

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) 8-Feb-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

44

22
08/02/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
8-Feb-21 .^ Array A .^ B [2, 5] .^ 3 = [2 ^ 3, 5^3]
(ii) Matrix operation exponentiation 45

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
8-Feb-21
program to generate a table of current, voltage and power dissipation. 46

46

23
08/02/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
8-Feb-21 Voltage: 0 20 40 60 80 100
Power: 0 40 160 360 640 1000 47

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
8-Feb-21 43 51
78 81 48

48

24
08/02/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.

8-Feb-21
To find A2, type A^2
49

49

25

You might also like