introduction to matlab programming with applications

52
Variables Variable is used to store a value, assigned by variable name = expression. x = x + 1 is correct. (Why?) Actually, the assignment operator is used to put a value in the variable, from right to left. For example, let a = 10, b = 20. Then a + b = 30. 1 >> a = 10; 2 >> b = 20; 3 >> a+b 4 5 ans = 6 30 ans is the default variable if you don’t assign one for it. Zheng-Liang Lu 41 / 92

Upload: others

Post on 07-Dec-2021

23 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Matlab Programming with Applications

Variables

Variable is used to store a value, assigned by

variable name = expression.

x = x + 1 is correct. (Why?)

Actually, the assignment operator is used to put a value in thevariable, from right to left.

For example, let a = 10, b = 20. Then a + b = 30.

1 >> a = 10;2 >> b = 20;3 >> a + b4

5 ans =6 30

ans is the default variable if you don’t assign one for it.

Zheng-Liang Lu 41 / 92

Page 2: Introduction to Matlab Programming with Applications

If you drop the semicolon (;) in the line, then the result willappear in the command window, say,

1 >> a = 102

3 a =4

5 10

Note that you may not drop semicolons in other programminglanguages.

The variable name is suggested to begin with a letter of thealphabet.

Cannot begin with a number, e.g. 1x is wrong.Cannot have a blank, e.g. x 1 is wrong.Cannot have +-*\%, e.g. x%1

Zheng-Liang Lu 42 / 92

Page 3: Introduction to Matlab Programming with Applications

Matlab is case-sensitive1, e.g. A and a are different.

The length of name is limited to 63 characters2.

namelengthmax returns what this maximum length is.

We avoid to use names of reserved words3 and built-infunctions.

The reserved words cannot be used as a variable, e.g. for, if,and end.i =√−1 and j =

√−1 by default.

If you set i = 1, then i = 1 until you clear i .

Variable names should always be mnemonic4.

1In general, programming languages are case-sensitive, but some are not,e.g. Fortran.

2Windows 7 (64-bit) in this case3Try iskeyword.4To assist your memory.

Zheng-Liang Lu 43 / 92

Page 4: Introduction to Matlab Programming with Applications

Data Type and Casting

Different types of variables occupy different size of memory.

All numeric variables are stored as the type double5 by default.Variables defined in type char are of size 2 bytes.Variables defined in type logical are of size 1 bytes.whos shows variables that have been defined in the commandwindow.

cast converts one variable to another type.

int8, int16, int32, and int64 are the integer types.

58 bytes = 64 bits.Zheng-Liang Lu 44 / 92

Page 5: Introduction to Matlab Programming with Applications

Computational Limits

Overflow occurs when the value is beyond the limits.

Zheng-Liang Lu 45 / 92

Page 6: Introduction to Matlab Programming with Applications

Scalar Variables

A scalar is a single number.

A scalar variable is a variable that contains a single number.

x is said to be a scalar variable if x ∈ R1 or C1.

The complex field, denoted by C, contains all the complexnumbers, in form of

a + bi ,

where i =√−1, and a, b ∈ R1.

Try x = 1 + i in the command window.

In math, C1 is equivalent to R2.So, x is stored as the type double with 16 = 8× 2 bytes.

Zheng-Liang Lu 46 / 92

Page 7: Introduction to Matlab Programming with Applications

Scalar Arithmetic Operators6

6See Table 2.1 Arithmetic Operations Between Two Scalars in Moore, p. 21.Zheng-Liang Lu 47 / 92

Page 8: Introduction to Matlab Programming with Applications

Display Format7

In Matlab, it is a common convention to use e to identify apower of 10, e.g. 1e5 = 100, 000.

7See Table 1.1-5 Numeric display formats in Palm, p. 15.Zheng-Liang Lu 48 / 92

Page 9: Introduction to Matlab Programming with Applications

Arrays

One of the strengths of Matlab is its ability to handlecollections of numbers, called arrays, as if they were a singlevariable.

An array is a systematic arrangement of objects, such as

Row vectors: ~x ∈ R1×n for any positive integer n.Column vectors: ~x ∈ Rn×1 for any positive integer n.Matrices: A ∈ Rn×m for any positive integers n,m.

Zheng-Liang Lu 49 / 92

Page 10: Introduction to Matlab Programming with Applications

The dimension of a general array is unlimited withoutregarding to the limit of memory space.

You can create an n ×m × k × · · · matrix for any positiveintegers n,m, k , . . .. (Try.)For example, let A be a 104 × 104 matrix. Then it takes762.94 MB in memory space.

Actually, all the arrays are stored in a continuous memoryspace.

Zheng-Liang Lu 50 / 92

Page 11: Introduction to Matlab Programming with Applications

Example

1 >> row vector=[1 2 3] % [ ... ] is used in arrays.2

3 row vector =4

5 1 2 36

7 >> column vector=[1;2;3] % semicolon is used to ...change rows.

8

9 column vector =10

11 112 213 314

15 >> matrix=[1 2 3; 4 5 6; 7 8 9] % define a 3-by-3 ...matrix

16

Zheng-Liang Lu 51 / 92

Page 12: Introduction to Matlab Programming with Applications

17 matrix =18

19 1 2 320 4 5 621 7 8 9

Zheng-Liang Lu 52 / 92

Page 13: Introduction to Matlab Programming with Applications

Some special matrices can be initialized by the followingfunctions:

Zheng-Liang Lu 53 / 92

Page 14: Introduction to Matlab Programming with Applications

Referring to Matrix Elements

Index of arrays in Matlab starts from 1 not 0.

Note that it does start from 0 in C.

Matrices can be indexed in two ways:

Subscripted indexingLinear indexing: matrices are arrays stored in a continuousmemory space in column major order.

1 >> matrix(2,3) % using subscripted indexing2

3 ans =4 65

6 >> matrix(8) % using linear indexing7

8 ans =9 6

Zheng-Liang Lu 54 / 92

Page 15: Introduction to Matlab Programming with Applications

Example: Deleting Elements

1 >> matrix(2,[1 3])2

3 ans =4

5 4 66

7 >> matrix(:,1)=[] % clear the first column vector8

9 matrix =10

11 2 312 5 613 8 9

Zheng-Liang Lu 55 / 92

Page 16: Introduction to Matlab Programming with Applications

Automatic Initialization of Array

linspace(·, ·, ·) initializes a linear vector of values.

1 >> x=linspace(0,10,5) % start, end, points2

3 x =4

5 0 2.5 5 7.5 10

You can also use colon operator (:) to create a vector. Forexample,

1 >> x=0:2:10 % start : increment : end2

3 x =4

5 0 2 4 6 8 10

logspace initializes logarithmically spaced values. (Try.)

Zheng-Liang Lu 56 / 92

Page 17: Introduction to Matlab Programming with Applications

Example: Invalid Vector Creation

1 >> x=1:-1:102

3 x =4

5 Empty matrix: 1-by-0

Zheng-Liang Lu 57 / 92

Page 18: Introduction to Matlab Programming with Applications

Strings

Let x = ’Arthur’. Then x stores a string.

1 >> x='Arthur'2

3 x =4

5 Arthur6

7 >>

Zheng-Liang Lu 58 / 92

Page 19: Introduction to Matlab Programming with Applications

Actually, x is an array whose elements store a character inorder.

1 >> x='Arthur';2 >> x(1)3

4 x(1) =5

6 A7

8 >>

Zheng-Liang Lu 59 / 92

Page 20: Introduction to Matlab Programming with Applications

Tricks in Arrays

It is easy to manipulate the arrays in Matlab. For example,

1 >> x='Arthur';2 >> x=[x ' meets Matlab.'] % string concatenation3

4 x =5

6 Arthur meets Matlab.7

8 >> x=[x; 'Matlab gives me fun.']9

10 x =11

12 Arthur meets Matlab.13 Matlab gives me fun. % Should be the same ...

length as the first line.

Zheng-Liang Lu 60 / 92

Page 21: Introduction to Matlab Programming with Applications

Cell Array

A cell array is a data type with indexed data containers calledcells, where each cell can contain any type of data.

Cell arrays commonly contain either lists of text strings,combinations of text and numbers, or numeric arrays ofdifferent sizes.

Zheng-Liang Lu 61 / 92

Page 22: Introduction to Matlab Programming with Applications

Example

1 >> A(1,1)={'This is the first cell.'};2 >> A(1,2)={[5+j*6 , 4+j*5]};3 >> A(2,1)={[1 2 3; 4 5 6; 7 8 9]};4 >> A(2,2)={{'Tim'; 'Chris'}} ;5 >> A6

7 A =8

9 'This is the first cell.' [1x2 double]10 [3x3 double] {2x1 cell }

celldisp(C ) recursively displays the contents of a cell array C .

Zheng-Liang Lu 62 / 92

Page 23: Introduction to Matlab Programming with Applications

Referring to Cell Array

Using curly braces, {·}, for the subscripts will reference thecontents of a cell; this is called context indexing.

Using parentheses, (·), for the subscripts references the cell;this is called cell indexing.

1 >> A{1}2 ans =3 This is the first cell.4 >> A(1)5 ans =6 'This is the first cell.'

More details can be found in here.

Zheng-Liang Lu 63 / 92

Page 24: Introduction to Matlab Programming with Applications

Structure Array

A structure array is a data type that groups related data usingdata containers called fields.

Each field can contain any type of data.

Access data in a structure using dot notation of the formstructName.fieldName.

For example,

1 >> student.name='Arthur';2 >> student.id='d00922011';3 >> student.scores=[80, 90, 100];4 >> student % show the content of student5 >>6

7 student =8

9 name: 'Arthur'

Zheng-Liang Lu 64 / 92

Page 25: Introduction to Matlab Programming with Applications

10 id: 'd00922011'11 scores: [98 99 100]

fieldnames returns the names of the fields contained in astructure variable.

rmfield removes a field from a structure.

You can pass structures to functions.

More details can be found here.

They are extremely useful in applications such as Matlab GUIand database management.

Zheng-Liang Lu 65 / 92

Page 26: Introduction to Matlab Programming with Applications

Symbols In Workspace

Zheng-Liang Lu 66 / 92

Page 27: Introduction to Matlab Programming with Applications

Basic Math Functions8

8See Table 3.1-1 in Palm, p. 114.Zheng-Liang Lu 67 / 92

Page 28: Introduction to Matlab Programming with Applications

Trigonometric Functions9

Recall that 1 rad =180◦

π.

9See Table 3.1-2 in Palm, p. 118.Zheng-Liang Lu 68 / 92

Page 29: Introduction to Matlab Programming with Applications

Summary:10

Parentheses (·)Arithmetic, e.g. (x + y)/z .Input arguments of a function, e.g. sin(1), exp(1).Array addressing, e.g. A(1) refers to the first element in arrayA.

Square brackets [·]: only used in array operations

e.g. x = [1 2 3 4].

Curly brackets {·}: only used to declare a cell array

e.g. A = {’This is Matlab class.’, x}.

10Thanks to a lively class discussion (Matlab-237) on April 16, 2014.Zheng-Liang Lu 69 / 92

Page 30: Introduction to Matlab Programming with Applications

1 >> Lecture 22 >>3 >> -- Programming Basics4 >>

Zheng-Liang Lu 70 / 92

Page 31: Introduction to Matlab Programming with Applications

“If debugging is the process of removing software bugs,then programming must be the process of putting themin.”

– Edsger W. Dijkstra (1930–2002)

Zheng-Liang Lu 71 / 92

Page 32: Introduction to Matlab Programming with Applications

Introduction to Matlab Programming

The Matlab command mode is very useful for simpleproblems, but more complex problems require a script.

The usefulness of Matlab is greatly increased by the use ofdecision making functions in its programs.

These functions enable you to write programs whose operationsdepend on the results of calculations made by the program.

Matlab can also repeat calculations a specified number oftimes or until some condition is satisfied.

This feature enables engineers to solve problems of greatcomplexity or requiring numerous calculations.

Zheng-Liang Lu 72 / 92

Page 33: Introduction to Matlab Programming with Applications

Program Design and Development

Design of programs to solve complex problems needs to bedone in a systematic manner from the start to avoidtime-consuming and frustrating difficulties later in the process.

An algorithm is an ordered sequence of precisely definedinstructions that performs a specific task in a finite amount oftime and space.

Zheng-Liang Lu 73 / 92

Page 34: Introduction to Matlab Programming with Applications

Building Blocks in Algorithms

There are three categories of algorithmic operations:

Sequential operations: These instructions are executed inorder.selection/conditional operations: These control structures firstask a question to be answered with a true/false answer andthen select the next instruction based on the answer.Iterative operations: These control structures repeat theexecution of a block of instructions.

Zheng-Liang Lu 74 / 92

Page 35: Introduction to Matlab Programming with Applications

Note that not every problem can be solved with an algorithm,so-called undecidable problems11.

Besides, some potential algorithmic solutions can fail becausethey take too long to find a solution.12

11See halting problem. Also see the computing theory.12Recall that the finiteness is one property of algorithms.

Zheng-Liang Lu 75 / 92

Page 36: Introduction to Matlab Programming with Applications

Programming Structures13

13See Figure 8.1 in Moore, p. 274.Zheng-Liang Lu 76 / 92

Page 37: Introduction to Matlab Programming with Applications

Structured Programming

An algorithm often must have the ability to alter the order ofits instructions using what is called a control structure.

Structured programming is a technique for designing programsin which a hierarchy of modules/functions is used.

Core concept: divide and conquer.In Matlab, these modules can be built-in or user-definedfunctions.

Structured programming14, if used properly, results inprograms that are easy to write, understand, modify, anddebug.

14See programming paradigms.Zheng-Liang Lu 77 / 92

Page 38: Introduction to Matlab Programming with Applications

Steps of Developing A Computer Program

1 (Problem formulation) State the problem concisely.

(Input) Specify the data to be used by the program.(Output) Specify the information to be generated by theprogram.

2 (Algorithm) Work through the solution steps by hand or witha calculator; use a simpler set of data if necessary.

3 (Programming) Write and debug the program.

4 (Verification) Check the output of the program with yourhand solution. Make sense?

5 (Generalization) If you will use the program as a general toolin the future, test it by running it for a range of reasonabledata values.

Zheng-Liang Lu 78 / 92

Page 39: Introduction to Matlab Programming with Applications

Flowcharts

Flowcharts make it easy to visualize the structure of aprogram.

It can display the various paths (called branches) that aprogram can take, depending on how the conditionalstatements are executed.

Why we need flowcharts?

Help developing the algorithm and program.Documenting programs properly is very important, even if younever give your programs to other people.

流程圖(Flow Chart)常用符號教學

Zheng-Liang Lu 79 / 92

Page 40: Introduction to Matlab Programming with Applications

Design Elements in Flowchart15

15See Table 8.3 Flowcharting for Designing Computer Programs in Moore, p.277.

Zheng-Liang Lu 80 / 92

Page 41: Introduction to Matlab Programming with Applications

Example16

16See Figure 8.2 in Moore, p. 277.Zheng-Liang Lu 81 / 92

Page 42: Introduction to Matlab Programming with Applications

Pseudocode

We use pseudocode in which natural language andmathematical expressions are used to construct statementsthat look like computer statements but without detailedsyntax.

For example,

1 if (student's grade >= 60)2 Print pass3 else4 Print failed5 end

Zheng-Liang Lu 82 / 92

Page 43: Introduction to Matlab Programming with Applications

Relational Operators17

Matlab has six relational operators to make comparisonsbetween arrays of equal size.

Note that all of them are binary operators, which need twooperands.

17See Table 8.1 in Moore, p. 274.Zheng-Liang Lu 83 / 92

Page 44: Introduction to Matlab Programming with Applications

Boolean Variables

Boolean variables contain only 0 and 1 for false and true,respectively.

For example,

1 >> x=2; y=5;2 >> z=x<y % Note that z is a logical variable.3

4 z =5

6 17

8 >> w = (y > x) ~= 1 % Note that w is a logical ...variable.

9

10 w =11

12 0

Zheng-Liang Lu 84 / 92

Page 45: Introduction to Matlab Programming with Applications

More Examples

1 >> x=0:1:10;2 >> y=10:-1:0;3 >> z=x<y % Note that z is a logical variable.4

5 z =6

7 1 1 1 1 1 0 0 0 0 0 08

9 >> w=x((x-y>0))10

11 w =12

13 6 7 8 9 10

In the second example, (x − y) > 0 return a logical vector.So, w((x − y) > 0) returns a partial vector of vector x whenthe corresponding element in (x − y) > 0 is 1.Equivalently, w = x([6 7 8 9 10]). (Try.)

Zheng-Liang Lu 85 / 92

Page 46: Introduction to Matlab Programming with Applications

Logical Operators

Zheng-Liang Lu 86 / 92

Page 47: Introduction to Matlab Programming with Applications

& vs. &&

1 clear all;2 clc3 % main4 x=[0 2 0 3]; % x is a numeric array5 y=[0 0 2 3];6

7 x>0 & y>0 % boolean array8 sum(x-y)>0 && sum(y-x)>0 % boolean scalar

The difference between | and || is similar except that | and ||do or operation.

Zheng-Liang Lu 87 / 92

Page 48: Introduction to Matlab Programming with Applications

Exercise18: & vs. ==

1 >> x=[0 2 0 4];2 >> y=[0 0 3 4];3 >> x==y4

5 ans =6

7 1 0 0 18

9 >> x&y10

11 ans =12

13 0 0 0 1

18Thanks to a lively class discussion (Matlab-237) on April 16, 2014.Zheng-Liang Lu 88 / 92

Page 49: Introduction to Matlab Programming with Applications

Example: Exclusive OR (XOR)

The exclusive OR function, denoted by xor(x , y) returns

0s where x and y are either both nonzero or both 0, and1s where either x or x is nonzero, but not both.

We can use the truth table19 to find the equivalent booleanexpression.

More interesting details of XOR can be found here.

Please write a program to do XOR operation on two booleanvariable x and y .

Input: boolean variables x , yOutput: xor(x,y)

19http://en.wikipedia.org/wiki/Truth_table

Zheng-Liang Lu 89 / 92

Page 50: Introduction to Matlab Programming with Applications

Truth Tables and Basic Logic Gates

Zheng-Liang Lu 90 / 92

Page 51: Introduction to Matlab Programming with Applications

1 >> x=[3 0 6];2 >> y=[5 0 0];3 >> z= (x |y)& ~(x&y)4

5 z =6

7 0 0 1

Note that the boolean expression of one specific statement isnot unique.

Zheng-Liang Lu 91 / 92

Page 52: Introduction to Matlab Programming with Applications

Precedence of Operators20

20See Table 1.2 Operator Precedence Rules in Attaway, p. 25.Zheng-Liang Lu 92 / 92