• 沒有找到結果。

Variables Variable is used to store a value, assigned by variable name = expression.

N/A
N/A
Protected

Academic year: 2022

Share "Variables Variable is used to store a value, assigned by variable name = expression."

Copied!
52
0
0

加載中.... (立即查看全文)

全文

(1)

Variables

Variable is used to store a value,assignedby variable name = expression.

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

Actually, the assignment operatoris 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

(2)

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

1 >> a = 10

2

3 a =

4

5 10

Note that youmay not drop semicolons in other programming languages.

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

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

(3)

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 ofreserved words3 and built-in functions.

The reserved words cannot be used as a variable, e.g. for, if, andend.

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.

(4)

Data Type and Casting

Different types of variables occupy different size of memory.

All numeric variables are stored as the type double5by 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 command window.

cast converts one variable to another type.

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

58 bytes = 64 bits.

(5)

Computational Limits

Overflow occurs when the value is beyond the limits.

(6)

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 complex numbers, in form of

a + bi , where i =

−1, and a, b ∈ R1. Try x = 1 + i in the command window.

In math, C1is equivalent to R2.

So, x is stored as the type double with 16 = 8 × 2 bytes.

(7)

Scalar Arithmetic Operators

6

(8)

Display Format

7

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

7See Table 1.1-5 Numeric display formats in Palm, p. 15.

(9)

Arrays

One of the strengths of Matlab is its ability to handle collections of numbers, called arrays, as if they were a single variable.

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.

(10)

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

You can create an n × m × k × · · · matrix for any positive integers n, m, k, . . .. (Try.)

For example, let A be a 104× 104matrix. Then it takes 762.94 MB in memory space.

Actually, all the arrays are stored in a continuousmemory space.

(11)

Example

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

2

3 row vector =

4

5 1 2 3

6

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

change rows.

8

9 column vector =

10

11 1

12 2

13 3

14

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

(12)

17 matrix =

18

19 1 2 3

20 4 5 6

21 7 8 9

(13)

Some special matrices can be initialized by the following functions:

(14)

Referring to Matrix Elements

Index of arrays in Matlab starts from 1not 0.

Note that it does start from 0 in C.

Matrices can be indexed in two ways:

Subscripted indexing

Linear indexing: matrices are arrays stored in a continuous memory space incolumn major order.

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

2

3 ans =

4 6

5

6 >> matrix(8) % using linear indexing

7

8 ans =

9 6

(15)

Example: Deleting Elements

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

2

3 ans =

4

5 4 6

6

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

8

9 matrix =

10

11 2 3

12 5 6

13 8 9

(16)

Automatic Initialization of Array

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

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

2

3 x =

4

5 0 2.5 5 7.5 10

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

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

2

3 x =

4

5 0 2 4 6 8 10

logspace initializes logarithmically spaced values. (Try.)

(17)

Example: Invalid Vector Creation

1 >> x=1:-1:10

2

3 x =

4

5 Empty matrix: 1-by-0

(18)

Strings

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

1 >> x='Arthur'

2

3 x =

4

5 Arthur

6 7 >>

(19)

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

1 >> x='Arthur';

2 >> x(1)

3

4 x(1) =

5

6 A

7 8 >>

(20)

Tricks in Arrays

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

1 >> x='Arthur';

2 >> x=[x ' meets Matlab.'] % string concatenation

3

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.

(21)

Cell Array

A cell array is a data type with indexed data containers called cells, 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 of different sizes.

(22)

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 >> A

6

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 .

(23)

Referring to Cell Array

Using curly braces, {·}, for the subscripts will reference the contents 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.

(24)

Structure Array

A structure array is a data type that groupsrelated data using data containers called fields.

Each field can contain any type of data.

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

For example,

1 >> student.name='Arthur';

2 >> student.id='d00922011';

3 >> student.scores=[80, 90, 100];

4 >> student % show the content of student

5 >>

6

7 student =

8

9 name: 'Arthur'

(25)

10 id: 'd00922011'

11 scores: [98 99 100]

fieldnames returns the names of the fields contained in a structure variable.

rmfield removes a field from a structure.

You can pass structures to functions.

More details can be foundhere.

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

(26)

Symbols In Workspace

(27)

Basic Math Functions

8

(28)

Trigonometric Functions

9

Recall that 1 rad = 180 π .

9See Table 3.1-2 in Palm, p. 118.

(29)

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 array A.

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 }.

(30)

1 >> Lecture 2

2 >>

3 >> -- Programming Basics

4 >>

(31)

“If debugging is the process of removingsoftware bugs, then programming must be the process ofputting them in.”

– Edsger W. Dijkstra(1930–2002)

(32)

Introduction to Matlab Programming

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

The usefulness of Matlab is greatly increased by the use of decision makingfunctions in its programs.

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

Matlab can also repeatcalculations a specified number of times or until some condition is satisfied.

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

(33)

Program Design and Development

Design of programs to solve complex problems needs to be done in asystematic manner from the start toavoid

time-consuming and frustrating difficulties later in the process.

An algorithm is anordered sequenceof precisely defined instructionsthat performs a specific task in a finite amount of time and space.

(34)

Building Blocks in Algorithms

There are three categories of algorithmic operations:

Sequential operations: These instructions are executed in order.

selection/conditional operations: These control structures first ask a question to be answered with a true/false answer and then select the next instruction based on the answer.

Iterative operations: These control structures repeat the execution of a block of instructions.

(35)

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

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

(36)

Programming Structures

13

13See Figure 8.1 in Moore, p. 274.

(37)

Structured Programming

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

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

Core concept: divide and conquer.

In Matlab, these modules can be built-in or user-defined functions.

Structured programming14, if used properly, results in programs that are easy to write, understand, modify, and debug.

(38)

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 the program.

2 (Algorithm) Work through the solution steps by hand or with a 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 your hand solution. Make sense?

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

(39)

Flowcharts

Flowcharts make it easy to visualize the structure of a program.

It can display the various paths (calledbranches) that a program can take, depending on how the conditional statements are executed.

Why we need flowcharts?

Help developing the algorithm and program.

Documenting programs properly is very important, even if you never give your programs to other people.

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

(40)

Design Elements in Flowchart

15

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

277.

(41)

Example

16

(42)

Pseudocode

We use pseudocode in which natural language and

mathematical expressionsare used to construct statements that look like computer statements but without detailed syntax.

For example,

1 if (student's grade >= 60)

2 Print pass

3 else

4 Print failed

5 end

(43)

Relational Operators

17

Matlab has six relational operators to make comparisons between arraysof equal size.

Note that all of them are binary operators, which need two

(44)

Boolean Variables

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

For example,

1 >> x=2; y=5;

2 >> z=x<y % Note that z is a logical variable.

3

4 z =

5

6 1

7

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

variable.

9 10 w =

11

12 0

(45)

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 0

8

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 when

(46)

Logical Operators

(47)

& vs. &&

1 clear all;

2 clc

3 % main

4 x=[0 2 0 3]; % x is a numeric array

5 y=[0 0 2 3];

6

7 x>0 & y>0 % boolean array

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

The difference between | and || is similar except that | and ||

do or operation.

(48)

Exercise

18

: & vs. ==

1 >> x=[0 2 0 4];

2 >> y=[0 0 3 4];

3 >> x==y

4

5 ans =

6

7 1 0 0 1

8

9 >> x&y

10

11 ans =

12

13 0 0 0 1

18Thanks to a lively class discussion (Matlab-237) on April 16, 2014.

(49)

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, and 1s where either x or x is nonzero, but not both.

We can use the truth table19 to find the equivalent boolean expression.

More interesting details of XOR can be found here.

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

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

(50)

Truth Tables and Basic Logic Gates

(51)

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 is not unique.

(52)

Precedence of Operators

20

20See Table 1.2 Operator Precedence Rules in Attaway, p. 25.

參考文獻

相關文件

A Boolean function described by an algebraic expression consists of binary variables, the constant 0 and 1, and the logic operation symbols.. For a given value of the binary

● Permission for files is easy to understand: read permission for read, write permission for modification, and execute permission for execute (if the file is executable). ●

• Copy a value from the right-hand side (value or expression) to the space indicated by the variable in the left-hand side.. • You cannot write codes like 1 = x because 1 cannot

this: a Sub-type reference variable pointing to the object itself super: a Base-type reference variable pointing to the object itself. same reference value, different type

even if bound changes on non-binary variables are present, such a subset can be used like the conflict detecting clause in SAT to represent the conflict in the conflict graph..

Note that this method uses two separate object variables: the local variable message and the instance field name.. A local variable belongs to an individual method, and you can use

The remaining positions contain //the rest of the original array elements //the rest of the original array elements.

grep - print lines matching a pattern. $ grep [OPTIONS]