introduction to matrices labolatory (matlab) as part of digital signal processing course

36
Introduction to MATrices LABolatory (MATLAB) as Part of Digital Signal Processing Course By Ahmed Fawzy Gad Faculty of Computers and Information (FCI) Menoufia University Egypt [email protected] عة المنوفية جامعلوماتت والملحاسبا كلية ا قسمعلومات الم تكنولوجياات الرقميةشارلجة ا معاMENOUFIA UNIVERSITY FACULTY OF COMPUTERS AND INFORMATION INFORMATION TECHNOLOGY DEPARTMENT DIGITAL SIGNAL PROCESSING معة المنوفية جا

Upload: ahmed-gad

Post on 24-Jan-2018

292 views

Category:

Education


0 download

TRANSCRIPT

Introduction to MATrices LABolatory (MATLAB) as Part of Digital Signal Processing Course

By

Ahmed Fawzy Gad Faculty of Computers and Information (FCI)

Menoufia University Egypt

[email protected]

جامعة المنوفية كلية الحاسبات والمعلومات

تكنولوجيا المعلوماتقسم

معالجة اإلشارات الرقمية

MENOUFIA UNIVERSITY FACULTY OF COMPUTERS AND

INFORMATION INFORMATION TECHNOLOGY

DEPARTMENT DIGITAL SIGNAL PROCESSING

جامعة المنوفية

MATLAB Course Syllabus

o MATLAB Installation

o MATLAB Packages

Definition

How to use a toolbox? (Java vs. MATLAB)

Examples of general and specific toolboxes

o MATLAB Versions and Releases

o What is MATLAB?

o Overview about MATLAB Desktop

o Windows and Layout

o Command Window

MATLAB Modes (Interactive & Scripting)

How Command Window interactive mode works (REPL)

Example 2+3

Statement separator and terminator (, and ;)

Example 1+1;2+3,5-3

ans variable

Multiple Commands at the Same Line (Comma ,)

Multiple-Lines Commands - Line Continuation (Ellipses

…)

Clearing Command Window (clc)

o Command History Window

Definition (stack)

Navigating between commands

Other ways to restoring and modifying commands

(drag&drop/copy&paste)

Deleting Commands (single, multiple, all)

o Workspace Window

Clearing Variables

o Current Folder Window

o Other Windows

Editor Window

o MATLAB Variables

o Naming Convention

o Checking variable name length and validity

o MATLAB Keywords

Difference between keyword and reserved variable

Avoiding confliction with these variables

o Commands related to variables

o Variable Data Types

o Signed and unsigned types

o Type Casting

o Command Window Numeric Display Formats

o MATLAB Operators and Corresponding Functions

o Arithmetic Operators

o Relational Operators

o Logical/Elementwise Operators

o Bitwise Operators

o Assignment Operators

o Set Operators

o Operators Precedence

o MATLAB Documentation

o Different ways to access MATLAB documentation

o Frequent Mathematical Functions

o Arithmetic Functions

o Exponential and Logarithmic Functions

o Trigonometry Functions

o Scripting

o Limitations of Command Window

o Opening the Editor Window (MATLAB Desktop & edit)

o Creating a new script

o Running a script using absolute path (run)

o Running a script in the current folder using name only

o How MATLAB finds scripts?

Current Folder

MATLAB Search Paths

o Summary of the different ways to run a script

o Scripts vs. Functions

o MATLAB Comments

o Matrices and vectors

o Everything in MATLAB is a matrix

o Introducing Array Editor Window

Example to edit a variable

Sharing data between MATLAB and MS Excel

o MATLAB array types

o Matrices and Arrays

Creating a vector (single row matrix)

Indexing a vector

Single value indexing

Multiple values indexing

o Example: Even indexed elements

o Example: Odd indexed elements

Creating a matrix (multi-row matrix)

Indexing a matrix

Single value indexing

Multiple values indexing

o Single row, multiple columns

o Multiple rows, single columns

o Multiple rows, multiple columns

o MATLAB Control Structures

o Selection Structures

if

if

if-else

if-elseif

if-elseif-else

if-elseif-elseif-…-else

switch

o Repetition Structures

for

while

o Figures and Plots

o figure

o plot

Common plot version plot(x,y)

Simple plot example

Relationship between plot and figure

Multiple plots commands but ignoring the figure

command

Multiple plots on the same figure

Using the plot command: single figure, multiple

plot

Using the hold on and hold off commands: single

figure, multiple plot

Using subplot command: single figure, multiple

plot

o title

o xlabel

o ylabel

o linspace

o axis

o xlim

o ylim

o Other plotting functions

stem

stairs

bar

scatter

MATLAB Installation

MATLAB Packages

Definition:

MATLAB consists of a set of toolboxes and each toolbox contains a set of pre-defined

functions that actually implements a commonly used code by programmers.

For example, programmers may need to calculate mean for a set of numerical values.

MATLAB actually implements a mean function packaged in a toolbox that can be used

easily by programmers.

How to use?

For a programming language like Java, it consists of a set of classes in a package and

multiple packages can be found in a single project.

To be able to use a class within a specific package you need to import that package

which appears tiresome.

But MATLAB makes things easier and not requires you to import the toolbox when

using it from your code. What is required is to install that toolbox.

When installing MATLAB, you have the option to select the toolboxes to be installed.

There are multiple toolboxes to install and toolboxes selection depends on your

purpose.

Examples of general and specific toolboxes:

The most common general toolboxes that can be used in a wide range of applications

are such as:

Signal Processing Toolbox

Statistics and Machine Learning Toolbox

Other useful toolboxes specific to the application of image analysis are like:

Image Acquisition Toolbox

Image Processing Toolbox

Computer Vision System Toolbox

Before being asked to create work by your hands it is required to understand the tools

you will use to create that work. So next is to understand MATLAB well before being

asked to create MATLAB scripts your own.

MATLAB Versions and Releases

The first step in learning most of the programming tools is to understand its history. The

history will help you have a good background about that tool and give you better

understanding about its capabilities.

For example, if you are asked to create an Android application the first step is to know

which version of Android the application targets. Android has different versions from

Android 1.6 Donut to Android 6.0 Marshmallow and each one may have some

differences from the other versions. Knowing which version you target will help you

decide which functions this version provides and you can use to build the application.

MATLAB has a strong history as its first version MATLAB 1.0 was published in 1983.

MATLAB is continuing in its race and now in 2016 its 9.1 version was released.

MATLAB has a new version every year. Each version of MATLAB has two releases

marked either as a and b.

For example, in 2013 MATLAB has two releases, one in the beginning of the year and

marked as a and another at the end of the year marked as b.

The release is written in this format: YearRelease. For example, 2013a, 2013b, 2014a,

2014b, 2015a, 2015b.

It is important to know which version and release of MATLAB you use because a

common error that occurs is using a function that is not supported by your installed

version of MATLAB. For example, if MATLAB 2010b was installed and you tried to use a

function provided by MATLAB 2012a, you will get an error.

So it is important to check whether the function is provided by the installed version or

not. Example is the timezones function that is supported in MATLAB 2015b

https://www.mathworks.com/help/matlab/ref/timezones.html.

What is MATLAB?

MATLAB is short for MATrices LABoratory.

We can`t say that MATLAB is a computer language and also can`t say it is just a

software.

MATLAB is not just software because if it was just a software so what is the explanation

that there is some programming within it?

Also it is not just a language because if so, what is the explanation about the tools found

in the program interface?

A better definition for MATLAB:

MATLAB is short for matrices laboratory which is software that provides an

environment to analyze data and perform scientific operations in addition to

incorporating programming. MATLAB allows some functions to be performed using GUI

without knowledge about programming at all but also it provides means of

programming allowing users to create their custom applications.

Some features can be accessed from both the MATLAB interface and programming.

Programming is a good way to do the job because it allows users to create their own

customized applications that can intelligently fit their purpose rather than depending on

the provided features from MATLAB. These features may be limited to a specific task

and may not completely fit the requirement of the user so some users prefer to create

their own applications from scratch.

Example of features provided from both interface and programming:

Neural Networks (NNs) can be created from MATLAB interface and also using

code.

Video frames can be displayed using MATLAB built-in program accessed from

interface and also can be displayed using code. But the MATLAB interface way to

capture frames has limitations because it is difficult to customize this interface to

fit your needs like specifying the frame size, bit depth, frame rate, and other

parameters. Using programming, it can be easier to customize the application

parameters to fit your needs.

In conclusion, features provided by MATLAB interface can be used for testing and on-

the-fly operations but programming is the better option to use to create your own

custom application because it provides better control.

MATLAB Windows

MATLAB mainly consists of 4 main menus that appear in the interface:

1. Command Window

2. Command History

3. Workspace

4. Current Folder window

These windows can be placed in different layouts that can be changed from MATLAB as

follows:

Desktop >> Desktop Layout

Then choose the appropriate layout.

You can close, lock, unlock, minimize or maximize any of these windows.

There are other windows like:

Script Editor Window

Array Editor Window

Command Window

MATBAB commands can be executed in two modes like Python:

1. Interactive Mode

2. Scripting Mode

Interactive Mode

Interactive mode is via the MATLAB desktop Command Window.

In the interactive mode, commands are entered in the Command Window command by

command in a style called Read Evaluate Print Loop (REPL). When one command is

entered by pressing enter, it will be read by MATLAB Command Window then get

evaluated or executed. The command may generate result and it will be printed. Finally

the console will loop again the read state and be ready to accept new commands.

Command Window has a number of properties:

Single-Line Commands

Command window is the main window used to enter commands regularly as single-line

commands next to the command prompt >>.

To execute a command in the Command window, write the command then press enter

to allow MATLAB to execute the command.

>> 2+3

Some commands will return result. If the command has no variable to store its results,

the default variable called ans is used.

Command window is not a text file as you are limited only to enter commands at the

current command prompt location and can`t go back and modify a command that

actually shown in the command window.

Ending statement by a semicolon

When no semicolon ; used after the command, its result is shown in the Command

Window after pressing enter. Note that semicolon not prevents results from returning

into the variables but prevents results from appearing in the Command Window.

If a command ended with a semicolon, its results are omitted from appearing in the

Command window.

In this case to print the variable value, use a function like disp() that accepts only a

string.

Multiple commands in the same line

Multiple commands can appear at the same line by separating them by comma or

semicolon. Note that semicolon is used to not print results of its statement.

So semicolon is regarded statement terminator an also terminator but comma is just a

statement separator.

Multiple-Lines Commands (Line Continuation …)

If the command was very long to appear in a single line, it can be extended to a second

line using ellipsis … . Example:

>> 2+ …

>> 3

Spaces do not affect commands so a=5; is similar to a = 5;

There are a set of commands related to the Command Window like:

clc

Command History

Commands are saved into a stack in the Command History window. Commands are

stored across sessions. So restarting MATLAB will not destroy the saved variables and

only destroyed if cleared manually.

Navigating between commands

We can navigate through commands entered previously using the up and down arrow

keys in the Command Window to avoid retyping the same commands and also you can

modify them.

Other ways to reenter and modify previously entered commands

By double clicking a command in the Command History window, it will be entered

automatically in the Command window as if it was written and then executed without

any modifications.

To modify it before execution, drag and drop or copy and paste the command, make

the required changes then press enter to execute it.

Delete Command History Window Commands

Commands stored in the Command History Window can be deleted individually or as

groups or even completely deleted:

Delete a single command: select it and press delete or right click the command

and select the "Delete Selection" option.

Delete multiple commands: select commands to be deleted and press delete or

right click any of them and select "Delete Selection" option.

Delete all commands: right click any of the commands in the Command History

Window and choose the last option "Clear Command History".

Workspace Window

Result of a command if any is stored into a memory variable that will appear in the

Workspace window. If the command was anonymous and not assigned to a variable, its

results will be stored in the ans variable.

Variables can be cleared using the clear command:

Clear a single variable: clear x

Clear multiple variables: clear x y z …

Clear all variables: clear all

As a summary for the first three windows, commands are entered and executed in the

Command window. Commands entered are stored in a stack in the Command History

window. If the commands return a result, it will be stored in variables in memory and

appear in the Workspace windows.

Current Folder

All paths are relative to the current folder.

It is used to show and modify the MATLAB current folder directory.

For each window, there is a corresponding command to set focus to that window:

commandwindow, commandhistory, and workspace.

MATLAB Variables

Naming Convention

MATLAB variables can use any combinations of a-z characters either small or capital and

numbers 0-9 in addition to underscore _. They can`t start with a number or underscore.

If a variable name consists of more than one word, you can combine them using

underscores or in a more recommended fashion by capitalizing the very first character

of words other than first. So instead of test_result use testResult.

Variable names has a maximum length equals to the value returned by namelengthmax

command that is relative to the system. Names larger than namelengthmax will be

truncated to namelengthmax.

To check if a string can be a valid variable name: isvarname(‘var’). It returns 1 for valid

variable names and 0 for invalid variable names.

MATLAB variables are case sensitive so variable var is different from Var.

There are a set of commands that are related to variables:

who, whos, clear/clear all, clear var1, clear var1, var2, …, exist.

Variable names can`t be one of the reserved or key words in MATLAB such as a built-in

function mean.

Difference between keyword and reserved word:

Keyword is a word that has special meaning in the language.

Reserved word is a word that is reserved by the language and can`t be used by the

programmer as a variable name.

Question:

if, for and while are keywords or reserved words?

Answer:

They are both keywords and reserved words. They are keywords because they have

special meaning in the language. They are reserved words because they can`t be used as

variable names.

In general, to check if a word is reserved word, try to use it as a variable name. If the

name was valid then it is not a reserved word.

There are a number of MATLAB built-in variables. Some of them have a constant value

and others can change value based on machine.

pi: The mathematical constant 𝜋.

i & j: Imaginary number which is the square root of -1 or √−1.

Inf or inf: Arithmetic representation of positive infinity floating-point values that

result from operations such as division by zero or overflow.

NaN or nan: Not a number to indicate values that can`t be real or complex such

as 0/0 or Inf/Inf or any operation involving NaN.

eps: The machine epsilon is the minimum distance between two floating-point

variables that MATLAB can recognize. If the difference between two variables is

less than epsilon of the machine, MATLAB will say that they are equal and

difference between them is 0. Example:

a=1;

b=1+eps; % b-a is eps.

b=1+eps/2; %b-a is 0 because difference between the variables is less than

epsilon.

realmax: Largest floating-point number in MATLAB. Overflow occurs if a number

is larger than this number and will be clipped to realmax. Some cases where

number is very larger than realmax the result is Inf rather than just overflow and

clipping.

realmin: Smallest floating-point number in MATLAB. Similar to realmax as

underflow occur if a number is less than it and if the number was very smaller

than it, results is 0.

intmax & intmin: Maximum and minimum integer values. They default to int32.

To find maximum/minimum for other integer types, specify them as follows

intmin/intmax(‘int8’).

pwd: Contains MATLAB current folder. pwd stands for Print Working Directory.

cd: Change MATLAB current folder. Example cd(‘C:/test’). cd stands for Current

Directory.

dir: Returns a list of folder contents.

date: current date

Note that all of these variables can have their value changed so be careful. This is

because one can assume that i=j= √−1. But the user may by mistake create a variable

named i or j. So if the user set i=5; then the old value will be overwritten and lead to

logical errors.

MATLAB Data Types

Don`t think that because MATLAB does not declare the variable type when the variable

is created that no data types exist for MATLAB. Data types actually exist.

Some programming languages like Java and C++ require variable type to be declared

explicitly by the programmer. MATLAB knows variable type implicitly from the assigned

data.

There are a number of built-in data types for MATLAB variables.

Each variable has a type and a range that specify its characteristics in addition to a set of

manipulators to perform operations over that type.

The type and operations are called classes.

Primitive data types in MATLAB including:

Integer: int8/uint8, int16/uint16, int32/uint32, int64/uint64

Floating-point: single, double % Any number is double by default.

Character: char

Logical: logical

Date Type Casting

There is a function with the same name as each type to convert data to that type.

Example, int8(5.4)

Change Command Window numeric display format

By default, MATLAB Command Window displays numeric results as short with 4 decimal

places.

To change this default format:

File >> Preferences >> Command Window >> Text Display >> Numeric Format &

Numeric Display.

Numeric formats available are such as short (default) 4 digits, long (15 digits), + (+/-

/blank for positive/negative/zeros results, bank (currency format with 2 digits), hex,

ratio.

Also numeric display or line spacing can be changed between loose and compact

formats.

These formats can be changed programmatically using the format function as follows:

format short % numeric format

format compact % numeric display

Programmatically just changes the format for a single MATLAB session. To maintain the

effect for future sessions, use MATLAB preferences.

Operators and Operators Precedence rules

Operators can be unary, binary or both.

Arithmetic Operators : + plus, - minus, * mtimes, .* times, / mdivide, ./ divide, ^

mpower, .^ power, mod, rem, --, ++

Relational Operators : == eq, ~= ne, > gt, < lt, >= ge, <= le

Logical Operators : && and, || or, ~ not, xor

Bit-/element-wise Operators : & bitand, | bitor, bitcom, bitxor

Assignment Operators : =

Set Operators : intersect, union

Arithmetic Operators precedence: (), ^, - negation, * / \, + -

MATLAB Documentation

MATLAB is composed from different toolboxes such as Database Toolbox, Computer

Vision Toolbox, Image Processing, Communications System Toolbox, in addition to

general MATLAB functions that is used across all MATLAB toolboxes.

MATLAB is well-documented.

Documentation of MATLAB can be accessed via different ways:

o Online at http://www.mathworks.com/help/matlab/

o Using the help command line. % help rat

o From MATLAB Desktop: Help >> Product Help.

MATLAB Functions

These are covered:

Some Arithmetic Functions

Relational Functions

Logical Functions

Bitwise Functions

Data Types Functions

Other Arithmetic Functions

abs(x)

power(x,y) === x^y

ceil(x) : round towards positive infinity

floor(x) : round towards negative infinity

fix(x) : round toward zero

round(x) : round to nearest integer

mod(x)

rem(x)

sign(x)

Exponent and Logarithms

sqrt(x)

nthroot(x,n) => √𝑥𝑛

exp(x) => 𝑒𝑥

pow2(x) => 2𝑥

log10(x) => log2(x)

log(x) => loge(x)

Trigonometry functions with radian argument

Radian sin asin cos acos tan atan sec asec …

Degree sind asind cosd acosd tand atand Secd asecd …

To convert an angle measurement from radian to degree: radtodeg(rad).

To convert an angle measurement from degree to radian: degtorad (deg).

Elementary Math Functions

factorial(x)

factor(x): decompose the number to its prime factors

isprime(x)

primes(x): list of primes less than or equal to the number

gcd(x,y)

lcm(x,y)

rat(x): rational fraction approximation of the number

rats(x): rational approximation of the number. Default string length is 13.

rats(x, strlen): rational approximation of the number.

Example: rat(pi), rats(pi), rats(pi, 7), rats(pi, 6/5/4/3/2), rats(pi, 20)

MATLAB Scripts

It is nice here to give a summary of what we have previously discussed.

MATLAB is a scientific tool that incorporates programming to perform several scientific

operations. MATLAB desktop consists of four main windows. MATLAB has several data

types and operators. The building block of MATLAB is its functions. Documentation can

be accessed via different ways.

Command Window can be used for simple calculations. It is difficult to create complex

calculations in Command Window where there are many commands are to be entered.

Limitations of Command Window:

It is used to enter command by command. If a program consists of 100

commands so we have to enter 100 lines in the command window one for each

command, press enter to process the command and continue executing other

commands.

If error occurred in a command, it is hard to manage it. Give an example of a

program that consists of 3 lines to divide two numbers a=2; b=0; c = a / b;, and

try to fix the error of dividing by zero to show how difficult it is to manage the

error.

Solution is to group these statements in a single file.

Scripts are just containers to commands that accept all commands entered in the

Command Window. MATLAB files are called scripts or M-files as they have .m extension.

Scripts are edited in a new window called Editor Window.

To open the Editor Window and create a MATLAB script:

From MATLAB desktop: File >> New >> Script

Using Command Line: edit

The Editor Window has many menus and menu items similar to MATLAB Desktop.

Write your MATLAB commands, save the file with a given name and make sure it has .m

extension, then run it. Scripts have the same naming convention as variables.

After saving the file it will appear under the current folder directory in the Current

Folder Window.

To execute a file, use the run MATLAB built-in function. It takes the complete/absolute

path of the file to be executed. For example, if you create a file named test.m saved in

this directory D:/programing/matlab, then it will be executed as follows:

run('D:/programing/matlab/text.m')

This command can be entered automatically by dragging and dropping the script into

the MATLAB Command Window.

But it is tiresome to enter the absolute path of the file to be executed. Life can be easier

by just entering the script name only to be executed in two ways:

1. Add the file to be executed under the current folder directory.

2. Add the path of the script to be executed in a MATLAB path.

How MATLAB finds scripts to be executed?

At first MATLAB searches its current directory and if the script file was not found then it

will search for that file in its search paths. It will stop when finding the first file with the

entered name.

There are disadvantages and advantages of using current directory and also of using

MATLAB search paths.

When using MATLAB current directory to run a script found in PATH1 it is required to

change the current directory of MATLAB to this path before running the file. When

running another file in another directory PATH2 it is required to change the directory

before running that file. So it is required to change the directory to match directory of

each file before it is to be executed. This is tiresome.

After changing the current directory to match the path of the file to be executed, just

the file name is entered like test for test.m.

The second option is to add the paths of the files you need to execute under MATLAB

search paths. MATLAB can find the files if they were under one of its search paths.

When entering the script name like test, MATLAB searches all of its search paths until

finding the first file named test.m and execute it.

Assume there are 100 search paths for MATLAB. So for MATLAB to find a specific file it

needs to search an average of 50 paths before finding the file. This takes time to locate

the file.

So using current working directory has an advantage of being simple and fast but has a

disadvantage running files in a single path only and it is required to change the path to

match the path of the scripts to be executed. Using MATLAB search paths make life

easier because you are not required to change the path to run the files but it takes much

time to locate the file.

For high-speed processors the time taken to locate the file under the MATLAB search

paths can be trivial.

So the different means to run a script in MATLAB are:

Manually entering the absolute file path in the run command.

Drag and drop the script in the Command Window.

Change current directory to match the file directory and just enter the file name

in the Command Window.

Add the file path in one of the MATLAB search paths and just enter the file name

in the Command Window.

All files to be executed by MATLAB must be under directory of current folder or one of

MATLAB search paths to make MATLAB able to find the file. Example, running a file

script1 allows MATLAB to search for the file, find it, and then execute it. Search is done

in MATLAB search space that is can be current path at Current Folder Window or

MATLAB paths.

Running a Script

Pressing F5 in the script window.

Type its name without .m in the Command Window: scriptName.

Using Editor Window: Debug >> Run scriptName.m. But this assumes that you

actually have the script opened and set to current script in Editor Window.

If the script to be executed is not in the current folder, a window will appear that asks if

to change the current folder to the folder containing the required script or to add the

script path to MATLAB path.

To display the contents of a script file without executing it, use the type command: type

scriptPath with/without .m extension as default extension is .m.

To open a file in the Editor Window for modifications:

Command Window: edit scriptPath with/without .m extension as default

extension is .m. Again the file must be found in current folder or one of the

MATLAB search paths.

In MATLAB desktop: File >> Open

If the script is under current folder directory, double-click it.

MATLAB Comments

To add a comment to a script line:

Add % before the line. Comments can be used in Command Window.

Right-click a line and select Comment option (CTRL+R).

To remove a comment:

Just delete the %.

Right-click a line and select Uncomment option (CTRL+T).

Note that creating or opening a script can be done from MATLAB Desktop or Editor

Window.

MATLAB Control Structures Control structures in MATLAB have a different syntax compared to Java and C++ and

other types of languages.

Statements can be enclosed inside another like if or for in different ways:

Using curly braces {} like Java and C++

Using keywords like end in MATLAB

Using indentation like Python

At first a common way to write for or if statements is to group all of their statements

inside two curly braces. But in MATLAB all statements that belong to a control structure

will be enclosed between the statement itself and the end keyword without using curly

braces.

Selection Structures

If

o If

o If-else

o If-elseif

o If-elseif-else

o If-elseif-elseif-…-else

switch

if

x=2;

if(x < 10)

disp('x < 10');

elseif(x < 20)

disp('10 < x < 20');

else

disp('x > 20');

end

switch

x=2;

switch(x)

case 1

disp('x is 1');

break;

case 2

disp('x is 2');

break;

case 3

disp('x is 3');

break;

otherwise

disp('No match');

end

Repetition Structures

for

while

for

Normal for loop in Java and C++ has three parts:

1. Loop variable with initial value

2. Condition

3. Increment or decrement

But in MATLAB there is a bit change. for loop in MATLAB has:

1. Loop variable with initial value

2. Maximum or minimum value

3. Increment or decrement

for loop in MATLAB has this format:

for loopVar=initialVal:inc-dec:lastVal

%Loop body

end

By default there is automatic increment by 1 after each loop. So k=1:5 is identical to

k=1:1:5.

for k=1:1:5

disp('Message');

end

The advantage of for loop is that all of its requirements are grouped in a single

statement. Just one statement will contain:

loop variable

initial value

condition

maximum or minimum value

increment and decrement after each loop.

But in while loop these parts are spread.

while

k=1;

while(k<5)

disp('Message');

k = k + 1;

end

In Java we can create infinite loop using both for and while loops. But in MATLAB we

can`t create an infinite loop using for.

Everything in MATLAB is a matrix Remember that MATLAB stands for MATrices LABoratory and thus the data that it

works on is matrix.

Every variable created in MATLAB is a matrix even if it consists of just a single value.

Examples:

a = 5; is equivalent to creating a matrix with just a single element.

Introducing Array Editor Window To edit an existing variable you can use the Array Editor window.

The Array Editor window can be accessed in two ways:

1. Double click the variable in the Workspace window.

2. Use the openvar command that accepts the variable name as a string. e.g.

openvar('test')

Example:

1. Open the previously created variable a in the Array Editor Window.

2. At first add additional elements in the same row without leaving empty cells.

3. Then add elements in a second row without leaving empty cells.

4. Finally add a single element in a third row without filling all the cells and

illustrate the zeros that are added automatically.

The Array Editor window will have a form similar to MS Excel that consists of cells.

The variable data will be in a matrix form even if the variable contains just a single value.

The variable can be edited by adding or removing additional cells of data.

Sharing Data between MATLAB & MS Excel

You can copy and paste data from the Array Editor to Excel and vice versa.

MATLAB array types MATLAB has three types of arrays:

1. Arrays

2. Cell arrays

3. Structure arrays

This course will focus on the first array type which is the normal and known type of

arrays.

Creating a vector Before creating an array or a matrix let us create what is simpler than a matrix which is a

vector. The vector is the building block of arrays and matrices.

A vector is just a single row or column from a matrix.

A vector is created by using two square brackets [].

Elements within the square brackets will be separated by spaces, commas, or

semicolons.

Spaces and commas just separate the elements but they still within the same row.

Semicolons make elements before and after it in subsequent rows.

So to create a row vector, just separate the elements using spaces or commas. To create

a column vector use semicolons.

Examples:

Create a row vector: [1,2,3,4,5] or [1,2 3 4, 5]

Create a column vector: [1;2;3;4;5]

View the created array in the Array Editor window.

A common function to create a linearly spaced vector of subsequent values is linspace.

Function declaration:

linspace(x1, x2, n)

It returns a vector of n elements starting from x1 and not exceeding x2.

The function is linear and linear means that data can be represented by a line and lines

change by a fixed amount.

So to reach x2 from x1 the line will change by a fixed amount.

To understand this function you should know the following:

1. What is linear?

2. How to find the amount of change to reach x2 from x1?

Example to understand what is linear:

The sequence 1, 3, 5, 7, 9 is a linear sequence because change occurs by a fixed amount

as each time 2 is added. The proof that this sequence is linear is that we can graph it as

a line.

But this sequence 1, 3, 5, 10, 12, 15 is non-linear because change occurs by a non-fixed

amount. Sometimes change occurs by 2 and another by 5 and another by 3. The proof

that this sequence is non-linear is that we can`t graph it as a line but as a polyline.

Example to understand how to find the amount of change to reach x2 from x1:

If you need to return 5 numbers in the range from 0 to 20 it is required to divide the

range between 0 and 20 into 5 parts.

Remember that the function is linear and linear means that change happens by a fixed

amount. So the amount of change from the first number to the second one will be equal

to the amount between second and third numbers and so on.

The rule to find spacing between elements or the amount of change is:

(x2-x1)/(n-1)

It is (n-1) not n because we need number of parts returned and not number of numbers.

1---2---3---4---5

Here number of parts is 4 but number of numbers if 5.

More explanation:

If you need to return 5 numbers in the range 0:20 then you should think that to return

the 5 numbers you need to divide the range into a number of parts. The number of parts

to return is always less than the number of numbers by 1.

So to return 5 numbers you divide the range into 4 parts.

Plotting sine wave:

arr = linspace(0, 20, 200);

result = sin(arr);

plot(arr, result);

Indexing a vector MATLAB indexing starts from 1 not 0.

A vector is indexed using the parentheses ().

Indexing can return:

1. Single value

2. Multiple values

Single Value Indexing

That is to specify the exact location of a single element to return. That is to specify the

element location in the row or column vector.

Example: v = [1 2 3 4]; v(2);

Multiple Values Indexing

Rather than specifying the index of a single element, a range of indices is to be specified.

To specify a range of indices, use the colon operator of this form start:change:last.

Where start is the starting index, last is the last index and change is the change that

happens to start to reach last.

Assume that you need to return the vector elements from the first element to the third

element. So the start index is 1, amount of change to make each time is 1 and finally thr

last index to return is 3. So the format used is v(1:1:3).

But v(1:3) also returns the same results as v(1:1:3). This indicates that change is by

default equal to 1.

Assume that you need to return elements starting from the second element to the fifth

one: v(2:1:5) or v(2:5).

What to do to return the even indexed elements in the vector? That is to start at index

2 and then return indices 4, 6, 8 and so on.

The idea is to make the change equal to 2 each time. V(2:2:8).

How to return the odd indexed elements? v(1:2:7)

What about v(3:1)?

This is invalid line and has logical error because it is impossible to reach the last index.

The change that occur to the first index (3) will not make it reach the last index (1)

because 3 is incremented by 1 each time and thus can`t reach the index 1.

Creating a matrix A matrix is a collection of vectors concatenated to each other.

To create a matrix in MATLAB, use semicolons to separate vectors in different rows.

Example:

mat = [1 2 3;4 5 6;7 8 9];

Indexing a matrix A vectors was just has a single dimension (row or column) and thus a single index is

expected to return a value from a vector.

But a matrix contains two dimensions (row and column) so it needs two indices to

return a single value. One index for row and another for column.

Single Value Indexing

Example: mat(1,3) this returns the matrix element at row 1 and column 3.

Multiple Values Indexing

1. Single row, multiple columns

2. Multiple rows, single columns

3. Multiple rows, multiple columns

It is also possible to return multiple values from a matrix using the colon notation.

The colon notation used for a matrix with two dimensions is as follows:

mat(start:change:last, start:change:last)

The first colon notation selects the rows and second one selects the columns.

Example: mat(1:3, 2:4) this command selects the rows 1, 2 and 3 and returns the

second, third, and fourth elements within these rows.

Figures and Plots

figure

To create a window and print graphs on it you need to use the figure command. This

command creates a new figure which is built-in to MATLAB and it is possible to draw on

that figure.

After opening the window we can draw on it.

There are many ways to draw on the figure like:

line: creates a line

rectangle

imshow: prints an image on the figure

plotting functions

o plot: Normal plot

o stem: Discrete plot

o scatter: Just draws circles at locations specified by the inputs x and y

without connecting them. It is also known as bubble plot.

o stairs:

o bar:

plot

In MATLAB it is very common to have multiple versions of the same function and you

select the version that is appropriate to your application.

A common version of the plot function accepts two inputs:

1. x

2. y

It has the form plot(x, y).

Simple plot example:

If there is a function of that form:

y = f(x) = x + 2

It is possible to have multiple values for x and find the y of each input.

If input is 1, 2, 3, 4 thus output will be 3, 4, 5, 6.

We can draw this function using the plot command.

So the complete commands to be used are:

x = [1 2 3 4];

y = x + 2;

figure

plot(x,y)

Relationship between plot and figure

It is not required to enter the figure command. By default when the plot command get

executed it opens a new figure if no existing figure is actually opened.

When just a single plot is to be created the figure command can be ignored.

But ignoring the figure command when multiple plots are to be created may lead

sometimes to problems.

Multiple plots commands but ignoring the figure command

For example:

Suppose that there are two functions to draw. If the figure command was ignored then

when entering the first plot command a new figure will be opened and the plot will

appear on it. When the second plot command gets entered it will replace the plot on the

active figure.

x = [1 2 3 4];

y1 = x + 2;

y2 = x + 10;

plot(x,y1)

plot(x,y2)

The solution is to open a new figure for each new plot.

x = [1 2 3 4];

y1 = x + 2;

y2 = x + 10;

figure

plot(x,y1)

figure

plot(x,y2)

For the first plot, it will search for an existing figure and it will find the figure that was

just created using the figure command.

For the second plot, it will search for an existing figure to use. It will find two figures that

were created by the two figure commands. Which one it will be used?

The answer is that the latest active figure is the one to be used.

Later you will know how to select a specific figure to plot on.

Multiple plots on the same figure

Opening a new figure for each new plot may create a large number of figures.

One figure may hold multiple plots.

This can occur in three ways:

Using the plot command: single figure, multiple plot

Using the hold on and hold off commands: single figure, multiple plot

Using subplot: single figure, multiple plot

Using the plot command: single figure, multiple plot

Another version of the plot function may accepts multiple x and multiple y plot(x1, y1,

x2, y2, x3, y3, …)

For example:

x = [1 2 3 4];

y1 = x + 2;

y2 = x + 10;

plot(x,y1, x,y2)

The advantage of this option is that it differentiates among the different functions

plotted by giving each one a different color.

Using the hold on and hold off commands: single figure, multiple plot

The second way is to use the hold on and hold off commands.

These commands are used if you are creating a single plot but this plot is created using

multiple plot commands.

If there are multiple plots created on one figure the last plot will override all the

previous plots.

But when entering the hold on command MATLAB knows that the subsequent plots will

be drawn on the same figure. So hold on tells MATLAB to continue drawing on the same

figure.

x = [1 2 3 4];

y1 = x + 2;

y2 = x + 10;

figure

plot(x,y1)

hold on

plot(x,y2)

This option assumes that you create a single plot and continue creating the plot. So for

the different plots created MATLAB does not differentiate among them and not give

each plot a different color. All plots will appear with the same color as if they were of

the same plot.

But if you are to create 3 plots and want 2 of them to appear on the same figure and

another one to appear on another figure then you can make the first plot, use the hold

on command that tells MATLAB to continue drawing on the same figure and enter the

second plot.

Then to tell MATLAB not to use that figure to draw next plots on it use the hold off

command. The hold off command tells MATLAB to open a new figure to draw.

Explain why the plot(x,x) overrides the previous plot:

x = [1 2 3 4];

y1 = x + 2;

y2 = x + 10;

figure

plot(x,y1)

hold on

plot(x,y2)

hold off

plot(x,x)

Using subplot: single figure, multiple plot

It is possible to divide the figure into multiple cells and make plots in these cells.

For example:

x = [1 2 3 4];

y1 = x + 2;

y2 = x + 10;

figure

subplot(1,2,1)

plot(x, y1)

subplot(1,2,2)

plot(x, y2)

Graph Axis Limits

What limits are used by MATLAB for axis?

MATLAB automatically selects the axis limits from the data.

Example:

x = [1 4 8 10 13];

y = x + 3;

plot(x,y)

MATLAB knows that x-axis starts from 1 to 13 so it will set the limits of the x-axis to 1

and 13.

It also knows that the minimum y-value will be 4 and the maximum is 16 so it will set the

y-axis limits to 4 and 16.

MATLAB uses the axis command to change the axis limits.

It has the following form:

axis([xmin, xmax, ymin, ymax])

To allow MATLAB to automatically chooses the minimum limits use –inf and for

maximum limits to inf.

xlim([xmin, xmax]) and ylim([ymin, ymax]) produces the same results as axis([xmin,

xmax, ymin, ymax])

Other Useful Functions:

disp

fprintf

input

pause

waitforbuttonpress

exit

quit

clf