# Introduction to Matlab Programming with Applications

Textbook 2018 369 Pages

## Excerpt

## TABLE OF CONTENTS

Table of Contents.. 2

About the author..3

Book Conventions..4

CH I - MATLAB BASICS..5

CH II - VARIABLES AND DATA TYPES..41

CH III - OPERATIONS ON MULTI-DIMENSIONAL VARIABLES..73

CH IV – PLOTTING..95

CH V - ADVANCED PLOTTING..116

CH VI - SYMBOLIC MATHEMATICS..149

CH VII - PROGRAMMING I - SCRIPT FILES..159

CH VIII - PROGRAMMING II – FUNCTIONS..168

CH IX - PROGRAMMING III – FLOW CONTROL..182

CH X - STRINGS, INPUT/OUTPUT AND FILE OPERATIONS..207

CH XI - BASIC GRAPHICAL USER INTERFACE (GUI – I)..240

CH XII - ADVANCED GRAPHICAL USER INTERFACE (GUI – II)..263

CH XIII - APPLICATIONS I - SIGNAL PROCESSING..267

CH XIV - APPLICATIONS II - IMAGE PROCESSING..307

CH XV - APPLICATIONS III – CLUSTERING AND CLASSIFICATION..350

LIST OF FIGURES USED IN THE BOOK..368

## ABOUT THE AUTHOR

### Dr. Aaron R. Rababaah

Dr. Aaron Rasheed Rababaah is an Associate Professor of Computer Science at the American University of Kuwait (Jan 2016 – Present). Dr. Rababaah held three other positions at three universities in USA before joining AUK; Dr. Rababaah was an Instructor at Indiana University of South Bend, Post-Doc researcher and Instructor at Tennessee State University and Assistant Professor then Associate Professor at University of Maryland Eastern Shore. Dr. Rababaah finished his B.Sc. in Industrial Engineering from University of Jordan, Jordan, his M.Sc. in Applied Computer Science from University of Indiana, USA and his Ph.D. from Tennessee State University, USA. Dr. Rababaah has five years of experience in IE and seven years in teaching at the college level. Dr. Rababaah has research interest in Intelligent Systems especially in robotics and machine vision. He has more than sixty publications and forty five professional presentations in several international journals and conferences. He was awarded several awards including two Distinguished Research Awards from a USA journal and a USA conference, Exceptional Leadership for ISO9000 accreditation, M.Sc. Scholarship/Academic Excellence Award, Ph.D. Scholarship, Thesis Showcase Award and Who’s-Who recognition for number of times. Dr. Rababaah has supervised, advised and referred senior projects, master theses, doctoral dissertations and number of journals. Dr. Rababaah has been funded several times to conduct research in his areas of expertise including, USA Department of Defense, US Army, NASA, USA Science foundation and Maryland Department of Education.

## CHAPTER I

### MATLAB BASICS

This chapter is an essential step to understand the MATLAB development environment before we attempt to explore the tools and techniques MATLAB provides to solve many problems in a spectrum of applications including math, science, technology and engineering. This chapter will help get acquainted with the needed skills and components to interact comfortably with MATLAB. It is highly recommended that you practice the lessons given in all chapters as you learn them as the source code will be listed in all examples.

### 1.1 MAIN COMPONENTS

Integrated Development Environment (IDE) is a common term to describe the advance tools/components provided to the programmers so they can edit, compile, run, debug, etc. their programs using one software. There are many IDEs exist in the area of computing such as M.S. Visual Studio, NetBeans, Eclipse, etc. in this section we will explore and navigate the IDE of MATLAB . There are four components in the IDE including: command window, command history, workspace and current directory. These components can be seen in Figure 1.1 and they are descried as follows:

#### 1.1.1 Command Window

This is the main and most important window that allows users/programmers to interact with the MATLAB. It is a command line based interactive tool where, the user types a command followed by arguments (if required) and then see the results on the same screen right after the command. We will demonstrate this procedure with few examples that you should try on your own. All examples in this book will be systematically formatted. They will be placed in a frame, labeled with an appropriate caption; the text needed by the user is highlighted with a blue color, the results are provided in black color and the lines of the example is numbered so we can explain each line separately.

[Figures and tables are omitted from this preview.]

Figure 1: Main Components of MATLAB IDE (Author’s own work)

Example 1.1: Using the Command Window (*pwd*)

[Figures and tables are omitted from this preview.]

001: The command *pwd* stands for *Present Working Directory*
. If you type this command and hit enter, the path of the current directory
that you are in will be displayed.

003: The word *ans* stands for *Answer*, which holds the
result of the last command you executed. Later on we will learn how to use
it in further commands.

005: This line shows the current directory the system currently at. Later
on we will learn how to read and write information and files from/to a
directory. *Work* is the name of the main directory of MATLAB by
convention. You can create your own sub directories under this parent
directory as we will see.

Example 1.2: Using the Command Window (*ls*)

[Figures and tables are omitted from this preview.]

001: The command *ls* stands for *list*. If you type this
command and hit enter, the contents of the current directory will be
displayed. Contents of directory include files such as text (.txt) files
that may contain data, code files (.m) that contains MATLAB programs and
other sub directories. As we progress, we will learn more file types that
we can process.

003: The symbol “*.”* stands for *this directory* and the
symbol “..” means the parent directory of the current one. See next example
for more details.

Example 1.3: Using the Command Window (*mkdir*)

[Figures and tables are omitted from this preview.]

001: The command *mkdir* stands for *make directory*. If you
type this command and add the name of the directory you want to create and
hit enter, a new directory with the specified name will be created as a sub
directory in the current directory.

002: We use *ls* to display the contents of the current directory
and verify the creation of the new directory.

004: Three elements can be seen in the list: “.”, “..”, and the newly created directory “dir01”.

Example 1.4: Using the Command Window (*cd*)

[Figures and tables are omitted from this preview.]

001: The command *cd* stands for *change directory*. If you
type this command and add the name of the directory you want to switch to
and hit enter, the current directory will be the one you specified.

002: We use *pwd* to verify the current directory.

You can always get out of a directory and go back to its parent by using
the command “*cd ..*”. See next example.

Example 1.5: Using the Command Window (*cd ..*)

[Figures and tables are omitted from this preview.]

#### 1.1.2 Command History

This component logs all commands have been executed and it keeps record of them even when you quit MATLAB . This is helpful when commands are long and tedious to retype so, you can simply use the mouse to select one or a group of commands and copy paste them or simply double-click the command and MATLAB will execute them. Check the current list of the command history (Figure 1.2) and try to double-click some of them and observe the effects on the command window.

[Figures and tables are omitted from this preview.]

Figure 1.2: Command History (Author’s own work)

#### 1.1.3 Workspace Window

This window keeps track of the variables currently exist in MATLAB workspace. Whenever you create a new variable {x, y, z, a, b, c, etc.} they will be logged in this window. Whenever you delete a variable, it is cleared off the list and you have no access to it. Currently, if you see the workspace window it should be empty since we have not created any variables. Let us create and delete some variables and observe the side effects. See next example for that.

[Figures and tables are omitted from this preview.]

Figure 1.3: Workspace Window (Author’s own work)

Example 1.6: Creating Simple Variables

[Figures and tables are omitted from this preview.]

001: Creates a variable “x” and assigns it the value “99”.

003: Displays the new variable “x” and its value on line 005.

007: Same for variable “y” as well, lines 007 – 011.

If no output is desired to be displayed after a command is executed, we need to add a semicolon “;” at the end of each command statement. Repeat Example 1.6 adding “;” to both assignment statements and observe the difference.

After you have created these two variables, you should see the workspace window has been updated with these two variables. The workspace window should look like the one in the figure below.

[Figures and tables are omitted from this preview.]

Figure 1.4: Updated Workspace after Creating Some Variables (Author’s own work)

Besides the workspace window, we can display the variables’ information using the command “whos” in the command window. See next example for a demonstration of this command and the associated information of variables in MATLAB .

Example 1.7: Attributes of Variables (*whos*)

[Figures and tables are omitted from this preview.]

001: *whos* displays attributes of all variables in workspace.

002: The different attributes of variables:

Name = the name of the variable

Size = number of rows X number of columns. Every variable in MATLAB is defined as a matrix which has a size of rows X number of columns. Therefore, our defined variables x and y are both matrices with a size of 1X1.

Bytes = number of bytes every element in the matrix occupies in memory.

Class = the data type of the variable. In this example the class is double which is the default for numerical data.

007: Gives information about the total number of elements (NOT the variables) in all variables, in this case we have two variables each has one element hence, we have 2 elements in total and these elements occupy 16 bytes in memory.

#### 1.1.4 Help and Documentation

This component is very helpful since it contains an elaborate documentation of MATLAB . To explore these help pages, click the icon indicated in Figure 1.5 and explore these documents.

Let us find some help for some function in MATLAB . For example if we want to know how to find the sin function of an angle, we type the key word “sin” in the search field as it can be seen in Figure 1.6. Besides being able to interactively use these windows to find help, there is the “help” command we can use from the command window. Simply type help followed by the name of the function you want and you will get an answer in the command window itself. Here is the same example of “sin” done with the “help” command.

#### Example 1.8: Getting help (help)

[Figures and tables are omitted from this preview.]

001: *help *sin the command and the argument “sin” (the name of the
needed function.

002: sin in MATLAB means the sine function.

003: Defines what is sin(x) means.

005: Recommends other related functions

[Figures and tables are omitted from this preview.]

Figure 1.5: Help and MATLAB Documentation Window (Author’s own work)

[Figures and tables are omitted from this preview.]

Figure 1.6: Example Using Help from MATLAB documentation (Author’s own work)

Example 1.9: Getting help (*doc*)

[Figures and tables are omitted from this preview.]

001: Use the *doc *command to open the documentation window and
point it at the specified key word, in this case “sin”. You should see the
same result as in Figure 1.6.

### 1.2 SCALAR ARITHMETIC OPERATIONS

The scalar arithmetic operations in MATLAB are quite intuitive as they are in many languages. Below is a table of the syntax and examples of each operation.

Table 1.1: Scalar Arithmetic Operations

[Figures and tables are omitted from this preview.]

Example 1.10: Scalar Arithmetic Operations

[Figures and tables are omitted from this preview.]

001: A combination of number of arithmetic operations

002: The result is stored in the variable “z”

004: The current value of “z”. the “e” means “10 to the power” so the value
= -9.4478 ´ 10^{3}

Example 1.11: Parenthesis in Scalar Arithmetic Operations

[Figures and tables are omitted from this preview.]

001: To enforce operation priority, use parenthesis

002: The result is stored in the variable “z”

004: The current value of “z”.

Example 1.12: Using the “ans” in Calculations

[Figures and tables are omitted from this preview.]

001: Arbitrary arithmetic operation

003: MATLAB saves the result in the variable “ans” (short for answer) since the result is assigned to a variable like x, y, z, etc.

005: The value of “ans”

007: Using “ans” in a new calculation. Watch the *sqrt* function
which means square root.

009: The result of the new calculation is stored in the variable “z”

011: The current value of “z”.

### 1.3 RELATIONAL OPERATORS

Relational operators are needed for comparison between variables and expressions and to test conditions. Below is the list of these operators and their definitions and we will demonstrate all of them in the following examples.

Table 1.2: Relational Operators

[Figures and tables are omitted from this preview.]

Example 1.13: Relational Operators

[Figures and tables are omitted from this preview.]

001: New variables to be used to demonstrate relational operators.

002: Testing the “<” operator. Observe that if the relation is true, the answer will be “1” else, the answer will be “0”. This applies for all relational operators.

038: New vector variables to be used with relational operators. v1 in 038 and v2 in 045.

052: When using a relation operator with a vector, the operator is evaluated one element at a time. So, in 052, every element in v1 is compared with the corresponding element in v2 and the output is a vector of “0”s indicating a false and “1”s indicating true. The size of the output vector is obviously the same is that of the input vectors.

058: Lines 058 – 074 see 052.

076: The relational operators are demonstrated with 2D matrices this time. m1 and m2 are created for that purpose.

092: Lines 092 – 106 demonstrate some relational operators on 2D matrices. See 052 to understand the meaning of the output matrix.

### 1.4 LOGICAL OPERATIONS

Logical operators are used to combine multiple relational operators or to operate on variables or expressions. The output of these logical operators are Boolean type represented as the numeric values of “0” and “1”. The next table lists and defines these operators and the following examples demonstrate their usage. It is important to define the convention of true “1” and false “0” in programming. A value is considered false or “0” if this value = 0. A value is considered true or “1” if this value ¹ 0 (this means all –ve and +ve numbers). See Table 1.4 for the truth table of these operator and see how they work.

Table 1.3: Logical Operators

[Figures and tables are omitted from this preview.]

Table 1.4: Truth Table of the Logical Operators

[Figures and tables are omitted from this preview.]

Example 1.14: Logical Operators

[Figures and tables are omitted from this preview.]

001: Creating some scalar variables to be used in demonstrating logical operators.

002: anding a and b. a = true, b = true è result is true “1”.

008: anding a and c. a = true, c = false è result is false “0”.

014: lines 014 – 061 just more examples with other operators.

062: lines 062 – 096 using the equivalent of the logical operators as functions.

### 1.5 BIT OPERATIONS

Logical operators work on variables, expressions, constants, etc. Whereas,
bit operations work on bits of all these. All data at the hardware level
are represented in bits for example the character ‘A’ is stored as
“01000001” and the number “123” is stored as “01111011”. To learn how data
is represented in different encoding schemes, please refer to the
references at the end. There are sometimes when we need to operate on these
bits but not the overall value. MATLAB provides a set of functions in the
category. All bit operators operate at the bit level. i.e., each bit in 1^{st} input is “operated on” with its corresponding bit in the 2 ^{nd} input, the result of each two bits is stored in the
corresponding location in the output variable. This rule applies to all
bit-wise operations. Table 1.5 lists and defines these functions. And the
following examples demonstrated these operators.

Table 1.5: Bit Operations

[Figures and tables are omitted from this preview.]

Example 1.14: Logical Operators

[Figures and tables are omitted from this preview.]

001: New scalar variables to be used in the bit operations.

002: The 8-bit binary representation of a = 00001011 and b = 00100001. These will be used in all of the following commands in this example. In 002, the result of bitor(a, b) = 43 which is in binary = 00101011. If we evaluate” a or b” one bit at a time we will get exactly 43 in binary.

008: the result of bitand(a, b) = 1 which is in binary = 00000001. If we evaluate “a and b” one bit at a time we will get exactly 1 in binary. Since the only matching “1”s are at location 1 and the rest will result in a bit-0.

014: Similar but xor instead.

020: The complement of 11 in 8 bits is 255 – 11 = 244. If you complemented the binary representation of “a” you will get 11110100 which is the binary representation of 244.

026: Lines 026 and 032 just getting the bits at locations 1, 3. See binary representation of “a” in 002.

038: Setting a bit will modify the value if a number. This example sets bit-7 to “1” while it was a “0” before. The new value is 75. “a” before = 00001011, “a” after = 01001011. The value if the after value is 75.

044: Shifting bits left/right will modify the value. In this command we shifted “a” 2 bits to the left (+ve argument). “a” before = 01001011, “a” after = 00101100. The value of the value after = 44.

050: In this command we shifted “a” 2 bits to the right (-ve argument). “a” before = 01001011, “a” after = 00000010. The value of the value after = 2.

### 1.6 NUMERAL SYSTEMS

It is quite often in programming that you need to convert from one numeral system to another. The most popular systems in programming are: binary, octal, decimal and hexadecimal. It is out of scope of this book to discuss the theory of numeral systems and their conversions but, we will give references at the end for interested readers. Table 1.6 lists and defines these conversion functions and the examples afterwards will demonstrate them.

Table 1.6: Numeral Systems Conversions

[Figures and tables are omitted from this preview.]

Example 1.15: Numeral Systems Conversions

[Figures and tables are omitted from this preview.]

001: An integer number is converted to binary.

007: The result from 001 is converted back to decimal for verification.

013: A hex number if converted into decimal.

020: The result from 013 is converted back to hex for verification.

027: Lines 027 – 043 test the function base2dec where, binary, octal and hex are the used.

046: Lines 046 – 062 test the function dec2base where, binary, octal and hex are the used.

### 1.7 MATHEMATICAL FUNCTIONS

MATLAB provides a very helpful set of mathematical functions. These functions are explained in Table 1.7 and demonstrated in the examples following the table.

Table 1.7: Numeral Systems Conversions

[Figures and tables are omitted from this preview.]

Example 1.16: Built-in Mathematic Functions

[Figures and tables are omitted from this preview.]

032: Observe that the ceil takes a value to the next whole number even if it is a very small fraction above a number.

056: See the floor how it rounds off any fraction above the floor whole number.

092: See also 103. They are identical functions.

109: round works different that floor/ceil. Based on most significant digit to the right of the decimal point, if < 5 è round down, if >= 5è round up.

145: Generate all primes <= 30.

151: Testing a number for being a prime.

### 1.8 DEFINING FUNCTIONS IN WORKSPACE

Besides the list of built-in mathematical functions discussed in section 1.7, MATLAB provides the ability to define your own function in the work space. There are number of ways to achieve this definition of a function, in the following examples we will demonstrate them with different situations.

Example 1.17: Defining your own Functions

We will demonstrate 5 ways to define functions in MATLAB :

1. As a string : f = ‘2 * x^3 - 3 * x^2 + 17*x – 19’

2. Using symbolic math toolbox: syms f x; f = 2 * x^3 - 3 * x^2 + 17*x – 19; (no quotes)

3. Using anonymous functions: f = @(x) 2 * x^3 - 3 * x^2 + 17*x – 19; (must specify the independent variable(s) in the parenthesis of @( ).

4. Using inline: f = inline( ‘2 * x^3 - 3 * x^2 + 17*x – 19’, ‘x’,’y’); (must specify the independent variable(s) as strings arguments after the string of the function definition all comma separated.

5. Using m-Files: this is all about programming, will leave it to the programming chapter.

[Figures and tables are omitted from this preview.]

001: Defining a function using an expression with single quotes.

007: To evaluate the function at any x-values, we need to define x first as in this line.

008: To evaluate any string function, call “eval” and pass the name of the function.

014: Lines 014 – 015 set x to new value and reevaluate “f”.

021: Lines 021 – 022 set x to new value and reevaluate “f”.

028: and 029 do clear and clc between sessions is a good idea to start fresh, unless you want to use current workspace variables.

030: syms (short for symbols) uses the symbolic math toolbox I MATLAB and it defines symbolic variables to be used in expressions, functions, etc.

031: Display the attributes of f and x and it can be observed that their classes are stated as “sym” meaning symbols.

039: Defining a function f as a function of symbolic expression. Observe that quotes must not be used here around the expression.

045: Lines 045 – 046 set x to an arbitrary value and evaluate “f”.

052: clc and clear 053

054: Defining f as an anonymous function using the “@” operator. No syms nor quotes are used to define the expression of the function.

060: To evaluate an anonymous functions, the function “feval” not “eval” and there is no need for x definition before calling “feval”, just pass a value or a variable as a second argument in the feval call.

066: Defining a function f using “inline“. Observe that the function expression must be quoted as a string, the second argument is the independent variable x as a string as well.

073: To evaluate an anonymous function just use it as you would use it in a math expression: write the name of the function followed by “( argument list)”.

080: 080 – 138 redefine the function f as a function of multi-variable namely x and y. Observe how the different ways described earlier define functions with multi variables and how they are evaluated.

145: This is an important example that applies to all expressions in MATLAB . In this example we added the “.” Before the operator “/” to account for array variables so this function can be applied to scalars as well arrays. The following lines 145 – 155 defines two arrays and evaluate the function using x, y inputs. It is important to mention that al arrays in an expression like this must have the same size.

168: Repeating line 145 but using scalar variables x and y this time. Observe that the output this time is scalar matching the type of the inputs which are scalars as well.

177: Defining an anonymous function.

178: Find the zero of the function with a given initial guess.

184: Repeat the command in 178 but this time add options to show the intermediate steps. Observe the different techniques listed and used in different iterations. Also observe that the answers in line 182 and 214 are identical.

215: This command plot the function so you can visualize the root and other behaviors of the function. See figure 1.7 – left. In Chapter IV and V will you will learn basic and advanced plotting techniques.

216: fzero is helpful if you want to find the intersection of two functions. e.g. sin(x) and exp(x). see Figure 1.7 – right for graphical verification.

[Figures and tables are omitted from this preview.]

Figure 1.7: Plotting a Function (Author’s own work)

## CHAPTER II

## VARIABLES AND DATA TYPES

Solutions of problems generally have three components: input, process and output. This chapter will discuss the input and output components from the variables and data types perspective. In real life, quantities don’t have the same type for example: measuring the room temperature is continuous in nature and need real number data type to hold its value. On the other hand, if we want to count how many people in a room, we need an integer data type to hold its value. Another example is a name of a person needs a string data type that can hold textual data. In MATLAB all of these and more data types are available and we will lean and use all of them as we proceed.

### 2.1 SCALAR VARIABLES

Scalar variables in MATLAB are single elements variables as opposed to vectors, arrays, matrices, etc. These variables describe a single quantity such as: height of a person, name of a person, current room temperature, current car speed, a GPA of a student in a semester, etc. let us demonstrate how to define some different scalar variables with the proper assignments of literal values.

Example 2.1: Scalar Variables

[Figures and tables are omitted from this preview.]

001: “temp” is assigned a real value since it is continuous quantity

007: “people_count” is assigned an integer value since it is discrete

013: “myName” is assigned a string value since it is meant to hold a string

One unique feature in MATLAB that is different from other programming languages is dynamic typing. Dynamic typing means that variables are not statically (permanently) bound to a data type but, they can be redefined to hold any quantity of any data type dynamically. Although MATLAB provides this feature liberally, programmers should be responsible to use it only as needed since it can lead to worsen code readability. See next examples to see how dynamic typing works and know some of its disadvantages.

Example 2.2: Dynamic Types

[Figures and tables are omitted from this preview.]

001: Defining variable “a” to be a string, see line 004 where it is redefined a an integer

002: Defining variable “b” to be an integer, see line 006 where it is redefined a real

003: Defining variable “c” to be a real, see line 005 where it is redefined a string

007: Observe that in this example we added the “;” at the end of each statement which suppressed the output to be displayed. Keep in mind that all statements were executed but the output was hidden do to the “;” in lines 001-006. When we removed the “;” in 007, we saw the value being displayed in 011.

In some cases, we need to delete some variables in our workspace because they are not in use any more or they are just dummy variables. There are different levels we can delete variables: single variable, multiple variables or all variables. See next example for a demonstration of all levels.

Example 2.3: Deleting Variables (*clear*)

[Figures and tables are omitted from this preview.]

001: Displays the current contents of the workspace.

015: Clears/deletes “a”. Watch the new list in 017-027, “a” disappeared.

029: Clears/deletes “b” and “c”. Watch the new list in 031-039, “b” and “c” disappeared.

041: Clears all variables. We can use “clear” with no arguments to clear all variables as well. Observe that the work space is empty after the last command. We can verify that from 042 using “whos “ which shows no output in line 043.

044: When you see too much clutter in the command window and you want to
clear the screen, use the command “*clc*”, try it and see its
effects.

In case your command line has syntax error, MATLAB reports a red-highlighted message indicating what is the error and its location. Pressing the up-arrow “Ù” or “” key on your key board you can bring back the previously entered command line and correct it then try again. To bring back older command lines, keep pressing the “” key till you find your command. The down-arrow “¯” works opposite to the up-arrow so, use both to move back and forth over your command line history.

Example 2.4: Command Line Error Correction (1)

[Figures and tables are omitted from this preview.]

001: Trying to calculate y from x. But, x has been deleted, it does not exist.

002: Error message indicating that “x” is undefined.

003: Two statements appear in one line. As long as the statements are separated by a “;”, “,” or a mix of bot, MATLAB allows multiple statements in one line. Any statement followed by “;” its result is not displayed and any statement followed by “,”, its result is displayed regardless of the order of the statements. Finally, The error is corrected and the command is tried again and succeeded.

007: The current value of “y”

Example 2.5: Command Line Error Correction (2)

[Figures and tables are omitted from this preview.]

001: Expression that has a repeated operator.

002: Error message indicating the location of the error which is the 2 ^{nd} repeated “/”.

003: The symbol “|” vertical bar or pipe is used as a pointer at the error location.

004: Description of the best guessed error type.

Example 2.6: Command Line Error Correction (3)

[Figures and tables are omitted from this preview.]

001: Trying to find sine of x. The sine is misspelled, in MATLAB it should be “sin”.

002: Error message indicating the error.

004: The error is corrected and the command is executed again.

008: The result is stored in “ans”.

### 2.2 DATA TYPES

It is considered an important issue in programming since it affects the efficiency of time and space of the program. I always like to make the analogy between programming and cooking as illustrated in Figure 2.1. I believe it helps to think about programming like cooking since it is very intuitive analogy. Let us discuss this analogy one item at a time:

**Kitchen vs. IDE**
: the kitchen is the place that contains all cooking means to facilitate
the cooking process. Also, IDE contains all needed tools to facilitate
programming.

**Chef vs. Programmer**
: Chef is the person who may prepare recipe and manages the cooking
process. Also, the programmer prepare the need code to implement a solution
for a problem.

**Recipe vs. Program**
: Recipe is a well-defined procedure to cook a certain dish. Also, a
program is a well define code instructions to solve a problem.

**Ingredients vs. Inputs**
: The inputs to a cooking process are the different food ingredients. Also,
the inputs for a program are the needed known quantities to be processed to
find the output.

**Containers vs. Data types**
: In order to manage the ingredients and cooked food, different containers:
pots, dishes, cups, etc. are needed. Also, to manage input/output variables
we need data containers/types to store these variables appropriately.

**Appliances vs. Toolboxes**
: Chef does not make a blinder or a microwave oven and then use it, he just
use it. Also, the programmer does not create the command window then use
it.

**Cooked Food vs. Program Display Results**
: When food is done, it is presented on a table for people to eat. Also,
when the input variables are processed they are converted into output and
reported presented on the screen for the users to make use of.

**Food Presentation vs. Output Formatting**
: Food need to be presented in a particular way that meets the consumer
demands. Also, the program output is formatted the way is required by the
user.

[Figures and tables are omitted from this preview.]

Figure 2.1: Analogy between Programming and Cooking (Author’s own work)

After this discussion, we realize that data containers play a significant role in the program efficiency. Therefore, programmers have a responsibility of deciding on the data types to be selected for the appropriate variables in input, process and output phases. The following table describes the available numeric data types in the MATLAB environment.

Table 2.1: Numeric Data Types Available in matalb

[Figures and tables are omitted from this preview.]

For intx (integer) and unitx (unsigned integer) data types, there are formulas to compute the ranges of these data types. We present these as follows:

**Intx Data Type:**

Let *n* be the total number of bits for a an int (not uint) data
type, *Low* be the lowest limit in the range and *High* be
the highest limit in the range of the data type, then:

[Figures and tables are omitted from this preview.]

**uintx Data Type:**

Let *n* be the total number of bits for a an uint data type, *Low* be the lowest limit in the range and *High* be the
highest limit in the range of the data type, then:

[Figures and tables are omitted from this preview.]

See next example on how find the min/max of the different data types in MATLAB using built-in functions. The example demonstrates two arguments for each data type which are the two extremes lowest and highest sizes. We can replace the argument with all other in-between sizes like ‘int16’, ‘int32’, etc. to get the sizes of the complete set of data types.

Example 2.7: Data Types (1)

[Figures and tables are omitted from this preview.]

Let us look at some examples where we can make use of table 2.1. to better choose data types for different variables.

Assume that we want to store the capacity of a class room in a variable called “roomCap”. What would be our choice from Table 2.1. Two questions need to be answered: min and max range of this variable. Min = 0, max = 100. So the closest data type is uint8. See next example for a demonstration.

Example 2.8: Data Types (2)

[Figures and tables are omitted from this preview.]

001: Defining a variable named “roomCap” and assigning an arbitrary value to it within the assumed range 0 <= roomCap <= 100.

005: Observe the default class and bytes of the variable, it is 64 bits = real double.

010: The data type of roomCap is converted from double to uint8.

014: The new size of roomCap = 1 byte. We were able to save 7 bytes otherwise wasted.

Assume that we want to store the mass of earth = 5.97219 × 10^{24}
kilograms, which data type would be appropriate? The closest would be the
single data type. See next example for a demonstration.

Example 2.9: Data Types (3)

[Figures and tables are omitted from this preview.]

001: Defining a variable named “earthM” and assigning the actual mass of earth in (kg).

005: Observe the default class and bytes of the variable, it is 64 bits = real double.

010: The data type of earthM is converted from double to single.

014: The new size of earthM = 4 bytes. We were able to save 4 bytes otherwise wasted.

Of course saving 7 bytes and 4 bytes would not a very significant gain but, you will realize that when we deal with arrays and matrices. To have a sense of what could we be saving, assume in example 2.7 that we needed a list of 1000 000 class room. So the total gain in memory for one variable would be 7 000 000 bytes.

### 2.3 MULTI-DIMENSIONAL VARIABLES

As we have discussed before, MATLAB defines all variables as matrices. In the previous examples we have used a single element or scalar variables. This section will deal with multi-dimensional variables.

#### 2.3.1 DEFINING AND INITIALIZING MATRICES

The first method is to initialize a matrix manually by entering the elements row by row. The elements in a row are separated by a space “ “ or comma “.” While the rows are separated by a semi-colon “;” and the entire body of the matrix is enclosed by square brackets “[ … ]”. See next example for a demonstration.

Example 2.10: Initializing Matrix Manually

[Figures and tables are omitted from this preview.]

001: Initializing the matrix m0 with arbitrary numbers manually.

002: m0 is displayed with proper matrix format

012: Observe the size attributes. In earlier example it was always (1x1) since variables were scalar whereas, in this example m0 is a (3 rows x 4 columns) matrix.

What if we need one column or one row vector? In case of a row vector, simply separate the elements by a space or comma and provide only one row with no “;”. In case of column vector, elements of the vector must be separated by “;”. See next example for these two cases.

Example 2.11: Initializing Row/Column Vector Manually

[Figures and tables are omitted from this preview.]

001: Initializing the vector v0 as a row-vector with arbitrary numbers manually. Also, v1 is initialized as a column-vector. Observe that the two statements appeared in one command line. Also, observe that the “ “ separates v0’s elements and “;” separates the elements of v1.

005: v0 is displayed as a row.

010: v1 is displayed as a column, lines 010 – 012.

018: Observe the size attributes. The size of v0 is (1 row x 4 columns)

019: The size of v1 is (3 rows x 1 column).

The manual initialization works for small sizes but, how do we populate large multi-dimensional variables such as 100 x 100 matrix or 1000 element vector, etc. See next examples for number of demonstrations. In these examples we will use number of built-in functions in MATLAB that automatically generate data according to passes sizes. These functions are summarized as follows: r = number of columns, c = number of columns. In all of these functions if a square matrix is needed we can pass only one argument rather than rows and columns.

*zeros*
(r, c): generates a (r x c) matrix with all elements set to “0”

*ones*
(r, c): generates a (r x c) matrix with all elements set to “1”

*rand*
(r, c): short for “Random”. Generates a (r x c) matrix with all elements
set randomly within the range [0, 1]

*randn*
(r, c): short for “Random Normal” generates a (r x c) matrix with all
elements set normally mostly within the range [-3, 3]

*randperm*
(n): generates a (1 x n) matrix with all position of elements set randomly
within the range [1, n]

*randbit(r, c): *
generates random bits matrix based on r-rows, c-columns

*randc(r, c):*
generates a random matrix [r, c] within the range [-0.5, +0.5]

*randint(r, c):*
generates a random matrix of 0’s and ones only no fractions. (bits)

*eye(n)*
: generates the identity matrix of a n size.

Example 2.12: Initializing Multi-Dimensional Variables Automatically (1)

[Figures and tables are omitted from this preview.]

001: m0 is automatically initialized using the built-in function zeros(r, c).

008: m1 is automatically initialized using the built-in function ones(r, c).

014: mr is automatically initialized using the built-in function rand(r, c).

022: mn is automatically initialized using the built-in function randn(r, c).

029: mp is automatically initialized using the built-in function randperm(n). Observe that this function was ran twice and we get different permutations (arrangements) between [1-9] every time we run this function.

035: A second run of the same function in 029.

041: Generating an identify matrix of size 4x4.

050: Demonstrating generating –ve and +ve numbers between [-0.5, +0.5]

059: Demonstrating generating random bit matrix.

Another method to automatically generate vectors is the linear spacing. This means to generate a sequence of numbers linearly displaced using three parameters: start value, increment and end value. There are two ways to do that, the linspace() function or the colon operator “:”. See next examples for these demonstrations.

Example 2.13: Initializing Multi-Dimensional Variables Automatically (2)

[Figures and tables are omitted from this preview.]

001: Using the “:” operator. Start Value : Increment : End Value

019: The increment value can be integer or a fraction as it is used in 019 as a fraction

025: The increment can be a negative number as it is used in 025.

031: In linspace function the parameters are different: (start value, end value, number of elements). So the increment is calculated implicitly from the three parameters as (end-start + 1)/number of elements.

049: The order in linspace can be descending as used in 049. Observe that the start value is larger than the end value.

In previous examples especially when dealing with “rand” function, we saw that the range of this function is [0, 1]. So the lowest value we can get is 0 and the max value we can get is 1. What if we need to randomly generate numbers with a different range say: min and max? To achieve that, we need to implement the following formula as a MATLAB expression:

[Figures and tables are omitted from this preview.]

Where:

min = the minimum value of the new range.

max = the maximum value of the new range.

rand = the built-in function that produces random numbers of the range [0, 1].

r = number of rows in the resulting matrix

c = number of columns in the resulting matrix

Example 2.14: Initializing Multi-Dimensional Variables Automatically (3)

[Figures and tables are omitted from this preview.]

001: Defining the minimum value of the desired scale

002: Defining the maximum value of the desired scale

003: Applying the formula in equation 2.2 to generate numbers between min and max

009: Generating a matrix instead of vector as in 003

017: If fractions are unwanted, we can use the function round().

025: A special case where the minimum value is “0”, the formula reduces to the one in 025. Observe that we used one argument in rand to produce a square matrix.

#### 2.3.2 MATRIX INDEXING

In the previous section we learned how to initialize and generate multi-dimensional variables and this section will discuss how to index the different elements or sub structures in a multi-dimensional variable. By indexing we mean to be able to access, store and retrieve elements at a certain location in the element using the rows, columns and higher dimensions. In defining matrices, we use square brackets “[ … ]” whereas in indexing we use parenthesis “(i, j, k, … )”, where i, j, k, … represent the subscripts/indexes of the dimensions of a variable. Let us demonstrate some examples.

Example 2.15: Matrix Indexing (1)

[Figures and tables are omitted from this preview.]

010: In this example, to access a certain element in the matrix m simply
add “( )” and insert the row number 1^{st} and the column number 2 ^{nd} m(r, c) of the target element. Observe the different
variations provided as examples in 010, 016, 022, 028, 034 and 040.

In the following examples we will use indexing to extract and manipulate the elements of a matrix. We will show how to extract a column, a row, a sub matrix and how to set these as will.

Example 2.16: Matrix Indexing (2)

[Figures and tables are omitted from this preview.]

001: Redisplaying the same previously generated matrix m.

010: Extracting the 1^{st} column and saving it to v.

019: Extracting the 1^{st} row and saving it to v.

025: Extracting a sub matrix from m as: rows 1 to 2 and columns 1 to 3.

032: Extracting the 5^{th} column and saving it to v.

040: Extracting the 3^{rd} row and saving it to v.

047: Extracting a sub row as elements from 3 to 7 indexes in row 3.

053: Regenerating the matrix m with a smaller size to save space in the next example in 060.

060: This is called linearization of the matrix m where, all elements are extracted as 1D array. Using the ( : ) operator is used to do that.

Example 2.17: Matrix Indexing (3)

[Figures and tables are omitted from this preview.]

009: Using the key word “end” indicates the last index of rows, columns or elements.

017: Setting a column of matrix to a specified vector.

026: Setting a row of matrix to a specified vector.

034: Deleting a column by setting it to empty vector “[ ]”.

042: Setting a sub matrix to a square matrix of zeros.

050: Flipping a matrix around the column dimension by rearranging the column indexes via a linear space in descending order using the “:” operator.

058: Flipping a matrix around the row dimension by rearranging the row indexes manually by providing a vector of indexes with the new arrangement of the rows.

If we have higher dimensional variables, we still deal with them similarly. Imagine the 3D data as layers of 2D matrices. You can access any element in the 3D by using 3 indexes (like coordinates x, y, z) as depicted in Figure 2.2. The next example demonstrates a 3D matrix.

[Figures and tables are omitted from this preview.]

Figure 2.2: 3D Matrix Visualization (Author’s own work)

Example 2.18: Matrix Indexing (4)

[Figures and tables are omitted from this preview.]

001: Creating a 3D matrix using the rand function passing 3 arguments of # of rows, # of columns and # of layers of matrices

023: Extracting the 1^{st} layer of the 3D matrix which the 1 ^{st} 2D matrix in the stack

031: Extracting the 1^{st} column in all layers. Observe that 3
columns were returned.

053: Extracting the 1^{st} column in all layers. Observe that 3
columns were returned.

069: Extracting a sub matrix from all layers. Observe that 3 sub matrices were returned

### 2.4 STRUCTURES AND CELL ARRAYS

Although the matrix data structure is dominant in MATLAB environment, there two more important data structures: structures (records) and cell arrays. Arrays are designed for homogeneous data i.e. all elements must have the same data types so we can have array of integers, array of reals, array of characters, array of strings etc. But we cannot mix between these data types in one array. But what do you do when we have objects that have heterogeneous attributes. For example a vehicle has these attributes: make (string), year (integer), engine size (real), color (string), etc. how do we save all of these heterogeneous data types in one array? Structures and Cell arrays come to rescue. The following examples demonstrate the concept and usage of these two structures.

Example 2.19: Structures

[Figures and tables are omitted from this preview.]

001: Defining a structure with the name “student” and assigning the first field name and value. The first field’s name is “name” and its value is ‘aaron rababaah’.

007: Lines 007 – 031 Add more fields and assign them their values.

041: Any time you type the name of the structure and hit enter, the system displays all fields and their respected values.

051: Lines 051 - 071 demonstrate how to create an array of structures. Three structures are created x, y and z. One structure at a time, they were saved in an array of structures “s”.

073: Lines 073 – 089 show how to access the structures one at a time in the array of structures “s”

097: Lines 097 – 109 show how to access the fields of individual structure in the array of structures “s”.

115: An example on how to use the fields if structure in an expression or calculation.

Example 2.20: Cell Arrays

[Figures and tables are omitted from this preview.]

001: Lines 001 – 006 create some heterogeneous variables to be used in a cell array. These arrays were: “a” an integer, 2D “b” a matrix, “c” a vector, “student” a structure.

007: Lines 007 – 010 stores the variables created in 001 – 006 in a cell array “ca”.

011: Displays the content of “ca”. Observe and verify the stored variables vs, the defined variables earlier.

017: Lines 017 – 037 Access the different objects in “ca”.

045: Observe the syntax to access sub elements of “ca”. In this line, ca{2} which is the 2D matrix is accessed via indexing and the element at (2,3) was retrieved.

052: Retrieving a sub element of “ca” and using it in an expression. Verify results.

058: Setting an element in “ca”. It is the first element which is a scalar integer.

060: “ca” is displayed tp verify results from 058.

064: Setting a sub element in “ca”. It is the name field of student structure.

070: c{4} the student structure stored at position 4 is displayed to verify operation in 064.

## CHAPTER III

## OPERATIONS ON MULTI-DIMENSIONAL VARIABLES

MATLAB provides a rich set of built-in functions that supports multi-dimensional variables such vectors, arrays, matrices, etc. in this chapter we will demonstrate many of them. The user is always encouraged to go beyond the material presented in this book and explore and learn more. In all of the examples in this chapter, we will use small size variables to save space.

### 3.1 MATRIX ARITHMETIC’S

The following operations are supported by MATLAB :

A+B, A-B, A*B, A.*B, A/B, A./B, A\B, A.\B, A^B, A.^B.

One thing we need to clarify is the difference between an operator by itself versus adding a period “.” in front of it. When we add a period “.” In front of an operator, the operator becomes an element-wise operation. For example, assuming A and B are two matrices and they are matrix multiplication compatible then, A * B = regular matrix multiplication whereas A .* B = element-wise multiplication. This means that each element in matrix A is multiply only once with its corresponding element in B and stored in the corresponding index on in the output matrix. The following examples will demonstrate all these operations.

Example 3.1: Matrix Arithmetic Operations

[Figures and tables are omitted from this preview.]

001: Creating an integer matrix, m1.

009: Creating an integer matrix, m2 with different size then m1 but multiplication compatible.

018: Creating an integer matrix, m3. Same size as m2.

027: Multiplying a matrix by a constant. (this works from left or right)

035: Dividing a matrix by a constant.

044: Subtracting a constant from a matrix.

053: Combining two matrices. This is called linear combination.

062: Matrix multiplication.

070: Element-wise multiplication. Observe the difference between the results (values and output matrix size) in 62 and 70.

079: This means that every element in m1 is raised to the power “2”. Observe that in all operations that have “.” In front of the operator, the size of the output matrix is the same as the input matrix.

087: m2 is divided by m3 using the element-wise division “./”. observe that since m3 has a “0” element at m3(1,3), therefore, we have a result of divide by zero = ¥ which is represented in MATLAB by “Inf”.

### 3.2 GENERAL MATRIX OPERATIONS

There are more operations on matrices than arithmetic operations. MATLAB supports a rich set of these operations as well as we will demonstrate. These operations include; transpose, flipping, sorting, etc. See next examples for number of demonstrations on these operations.

Example 3.2: General Matrix Operations

001: Creating a new matrix m.

010: Computing the transpose of m using the “’” operator.

019: Computing the inverse of m using the function “inv”.

028: Computing the determinant of m using the function “det”.

034: Computing the rank of m using the function “rank”.

040: Extracting the diagonal elements of m using the function “dia”.

049: Extracting the lower triangle of m using the function “tril”.

058: Extracting the upper triangle of m using the function “triu”.

067: Flipping m left-right using the function “fliplr”.

076: Flipping m up-down using the function “flipud”.

085: Reshaping m from 4x4 into 8x2. Observe that in reshape, you must maintain the total number of elements constant before and after. In 085, before = 16 elements and after = 8x2 = 16 as well. If it changes, MATLAB issues an error.

098: Reshaping m to 2x8. Again, number of elements is preserved at 16.

105: Reshaping m to 1x16. Again, number of elements is preserved at 16.

111: Reshaping m to 2x2x4 (3D matrix). Again, number of elements is preserved at 16.

136: Using the “cat” (short for concatenate) function to combine
size-identical matrices along a specified dimension in a multi-dimension
variable. Observe that we concatenated the given matrices along the 3 ^{rd} dimension which means we made the output structure 3 layers
of 2D matrices.

159: vertcat: concatenates a list of matrices vertically. Observe the resulting matrix after concatenating m1 and m2 on lines 163 – 168. m1, m2 and m3 are defined in 136.

171: horzcat: concatenates a list of matrices horizontally. Observe the resulting matrix after concatenating m1 and m2 on lines 175 – 177.

## Details

- Pages
- 369
- Year
- 2018
- ISBN (eBook)
- 9783668696150
- File size
- 13 MB
- Language
- English
- Catalog Number
- v420539
- Institution / College
- American University of Kuwait
- Grade
- 4.0
- Tags
- Matlab Programming