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

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

Matlab is case-sensitive^{1}, e.g. A and a are different.

The length of name is limited to 63 characters^{2}.
namelengthmax returns what this maximum length is.

We avoid to use names ofreserved words^{3} 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 mnemonic^{4}.

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

### Data Type and Casting

Different types of variables occupy different size of memory.

All numeric variables are stored as the type double^{5}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 command window.

cast converts one variable to another type.

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

58 bytes = 64 bits.

### Computational Limits

Overflow occurs when the value is beyond the limits.

### 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 ∈ R^{1} or C^{1}.

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

a + bi , where i =√

−1, and a, b ∈ R^{1}.
Try x = 1 + i in the command window.

In math, C^{1}is equivalent to R^{2}.

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

### Scalar Arithmetic Operators

^{6}

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

### 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 ∈ R^{1×n} for any positive integer n.

Column vectors: ~x ∈ R^{n×1} for any positive integer n.

Matrices: A ∈ R^{n×m} for any positive integers n, m.

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 10^{4}× 10^{4}matrix. Then it takes
762.94 MB in memory space.

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

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

17 matrix =

18

19 1 2 3

20 4 5 6

21 7 8 9

Some special matrices can be initialized by the following functions:

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

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

### 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.)

### Example: Invalid Vector Creation

1 >> x=1:-1:10

2

3 x =

4

5 Empty matrix: 1-by-0

### Strings

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

1 >> x='Arthur'

2

3 x =

4

5 Arthur

6 7 >>

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

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

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

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

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

### 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'

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.

### Symbols In Workspace

### Basic Math Functions

^{8}

### Trigonometric Functions

^{9}

Recall that 1 rad = 180^{◦}
π .

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

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

1 >> Lecture 2

2 >>

3 >> -- Programming Basics

4 >>

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

– Edsger W. Dijkstra(1930–2002)

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

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

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

Note that not every problem can be solved with an algorithm,
so-calledundecidable problems^{11}.

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

### Programming Structures

^{13}

13See Figure 8.1 in Moore, p. 274.

### 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 programming^{14}, if used properly, results in
programs that are easy to write, understand, modify, and
debug.

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

### 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)常用符號教學

### Design Elements in Flowchart

^{15}

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

277.

### Example

^{16}

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

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

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

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

### Logical Operators

### & 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.

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

### 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 table^{19} 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)

### Truth Tables and Basic Logic Gates

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.

### Precedence of Operators

^{20}

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