• 沒有找到結果。

# Introduction to MATLAB Programming with Applications

N/A
N/A
Protected

Share "Introduction to MATLAB Programming with Applications"

Copied!
50
0
0

(1)

### Introduction to MATLAB Programming with Applications

Zheng-Liang Lu

Department of Computer Science and Information Engineering National Taiwan University

MATLAB 323 Spring 2020

(2)

1 >> Lecture 0

2 >>

3 >> -- Introduction

4 >>

(3)

### Class Information

• Instructor: Zheng-Liang Lu

• Email: d00922011@ntu.edu.tw

• The course website is

http://www.csie.ntu.edu.tw/˜d00922011/matlab323.html.

• All lecture slides are organized in English and will be modified if necessary.

(4)

### Teaching Philosophy

• I try to lower the barriers to entry.

• I provide resources as many as possible.

(5)

(6)

### What Can A Program Do?

• A programis an implementation of an algorithmexpressed in a specific programming language.

(7)

### Algorithms In A Nutshell

1

• An algorithm is a well-definedcomputational procedurethat takes necessary information asinput and produces ancorrect answer asoutput.

• Simply put, an algorithm is a procedure that solves a specific class of problems, like a recipe or a cookbook.

(8)

• An algorithm has properties as follows:

Definiteness: all steps are precisely defined.

Finiteness: for any input, the algorithm must terminate after a finite number of steps (time).

Effectiveness: operations are basic enough (e.g. + − ×÷) to be able to done exactly and in a finite number of steps.

• Note that an algorithm could be expressed not only in programming languages, but also in human languages, flow charts, andpseudo codes.

(9)

### Example: Greatest Number

• Let A be a list of numbers.

• For example, consider A = {1, 7, 9, −2, 4}.

• Then it is clear that the answer is 9.

• Now propose an algorithm which finds the greatest element in for any list of numbers.

Input: A.

Output: the greatest element in A.

• Try a top-down approach in your native language?

(10)

### Optimal Solution

• Let A(1) be the first element of A and so on.

• The symbol ← is a copy operator from right to left.

1 max <- A(1)

2 for i <- 2 ~ n

3 if A(i) > max

4 max <- A(i)

5 end

6 end

7 return max

• In Line 1, why not max ← 0 but max ← A(1) ?

• You may extend this solution to more questions:

(11)

### Remarks

• Program design ≈ data structures + algorithms

Data structures: organize your data in an efficient way

Algorithms: process your data so that you can derive the solution

• In some sense, we can say that programming languages are less important than the two above.

• Here we will learn programming concepts and classical algorithms in MATLAB.

(12)

(13)

### Command Window

• Let’s try a greeting, “Hello, MATLAB.”

1 >> disp("Hello, MATLAB.");

disp takes thestringas input and outputs it on the screen.

A string isdouble-quotedin MATLAB.

• The convention in the slides is as follows:

Boxes show the listings for sample programs.

Important words and sentences are highlighted in red.

Words in blue are reserved words.

Bold words in black are functions.

(14)

### Errors

• MATLABinterrupts your program if anerror occurs.

• Don’t be frustrated by these red lines.

• Most of these errors detected by MATLAB aresyntax errors andruntime errors, which can be avoided by more practices.

• Logic errors cannot be found by the machine itself!

(15)

“Why do we fall sir? So that we can learn to pick ourselves up.”

– Alfred Pennyworth, Batman Begins (2005)

(16)

• help followed by the command name shows the usage of that command, for example,

1 >> help disp

2 ...

• The reference page also provides the detail of commands with fruitful examples.

(17)
(18)

### Debut: Your First MATLAB Program

1 % This is my first MATLAB program.

2

3 clear; % Clear all variables stored in the workspace.

4 clc; % Clear the screen.

5 % Main program

6 disp("Hello, Matlab.");

• The lines which begin with % are treated as comments which won’t be executed.

• The command clear is used to release all the variables in the workspace2.

(19)

• To run this program, we need to saveto a file, for example, helloworld.m.

• Click the Run button.3

• Alternatively, press F5 for saving the file and executing the program.

1 >> helloworld

2

3 Hello, world.

(20)

• Press ctrl + rto comment lines.

• Press ctrl + tto de-comment lines. (Useful!)

• The contiguous comment lines starting from the top of file are regarded as the program document.

1 >> help helloworld

2

3 This is my first MATLAB program.

• We can easily organize the program by these two hot keys during the trial-and-error stage.

(21)

1 >> Lecture 1

2 >>

3 >> -- Data, Data Types, and Operators

4 >>

(22)

### Data Types

• Everything is encoded in binary, aka bit (either 0 or 1).

Note that 1 byte is equal to 8 bits.

• How many bits do you need to store a value?

Not depending on the value itself!

The type determine its size!4

• We have two different numeric types: integers and real numbers (more precisely, floating points5).

An int value takes 32 bits.

(23)

### Computational Limits

• It is a common convention to use e to identify a power of 10,

(24)

### Numerical Error

7

• By default, MATLAB treats every numeric value as double.

• However, these double values only approximate real numbers.

For example, 0.5 − 0.1 − 0.1 − 0.1 − 0.1 − 0.1 =? (Why?)

Is 3.14 + 1e20 − 1e20 equal to 3.14 + (1e20 − 1e20)?

• Finite precision of computations involving floating-points is the main cause of numerical error.6

(25)

### Variables & Assignments

• A variable is used to keep a value or values.

• A common statement looks like

var = expression,

where var should be a variable and the expression could be a mathematical expression or a function call.8

For example, suppose x = 0.

Then run y = x + 1 and so y = 1. (Trivial.)

• How about x = x + 1?

Theassignment operator (=) is defined to assign a value to the variable,from right to left.

This expression acts like a counter, widely used in loops.

(26)

### Semicolon

1 >> a = 10;

2 >> b = 20;

3 >> a + b

4

5 ans =

6

7 30

• The variable ans is used by default if you don’t assign one for the immediate result.

• If you drop the semicolon (;) in Line 2, then the immediate result will appear in the command window.9

(27)

### Variable Naming

• Variable names should always be mnemonic.

• The name length is limited to 63 characters.10

• MATLAB is case-sensitive (e.g. A and a are distinct).

• We may use underscores ( ) or use CamelCase.11

• We avoid to use names ofreserved words12 and built-in functions.

i =

−1 and j =

−1 by default.

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

pi and sin are also the names which are not to be overloaded.

10The function namelengthmax returns the maximum length allowed in

(28)

### Scalar Variables

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

The complex field, denoted by C, contains all the complex numbers

a + bi , where i =

−1, and a, b ∈ R.13

Try x = 1 + i .

• Scalar variables are usually used as model parameters.

• For example,

pi = 3.141592653589793.

(29)

(30)

### Arrays

• An array is a collection of elements, each identified by indices.

• For math, arrays could be

row vectors: u ∈ R1×n for n ∈ N.

column vectors: u ∈ Rn×1for n ∈ N.

matrices: A ∈ Rn×m for n, m ∈ N.

• Arrays can be said the simplest (and the most important) one of data structures.

(31)

### Example

1 >> row vector = [1, 2, 3] % [] denotes an array.

2

3 row vector =

4

5 1 2 3

6

7 >> col vector = [1; 2; 3] % Semicolons change rows.

8

9 col vector =

10

11 1

12 2

13 3

14 15

(32)

18 >> A = [1 2 3; 4 5 6; 7 8 9]

19 20 A =

21

22 1 2 3

23 4 5 6

24 7 8 9

• You can create an n × m × k × · · · matrix for n, m, k, . . . ∈ N.

For example, a 104× 104 matrix takes 762.94 MBytes in memory.14

• The number of dimensions of arrays is unlimited without regarding to the limit of the memory space.

(33)

### Alternatives for Vector Creation

• The function linspace(start, end, nPts) generates a vector of uniformly incremented values.15

1 >> x = linspace(0, 10, 5)

2

3 x =

4

5 0 2.5 5 7.5 10

(34)

• You can also create a vector by using the colon operator as follows:

start : step size : end

1 >> x = 0 : 2 : 10

2

3 x =

4

5 0 2 4 6 8 10

• This is widely used to createindex arraysto manipulate arrays.

1 >> x = 1 : 5 % Default step size = 1

2

(35)

• You could create a null vector, say:

1 >> x = 1 : -1 : 5

2

3 x =

4

5 Empty matrix: 1-by-0

• It will be useful later!

(36)

• Some special matrices can be initialized by the following functions:

(37)

• We often use subscripted indexing like the way in math.

• Rarely use linear indexing: column major order.16

1 >> A(2, 3) % Using subscripted indexing.

2

3 ans =

4

5 6

6

7 >> A(8) % Using linear indexing.

8

9 ans =

10

11 6

(38)

1 >> A([1 3], [1 3]) % Range selection.

2

3 ans =

4

5 1 3

6 7 9

7

8 >> A(2, 2 : end - 1)

9

10 ans =

11

12 5

(39)

1 >> A(:, 2) = [] % Deleting the 2nd column.

2

3 A =

4

5 1 3

6 4 6

7 7 9

8

9 >> B = [A, A] % Merge A and A into B.

10 11 B =

12

13 1 3 1 3

14 4 6 4 6

15 7 9 7 9

(40)

### Cells and Cell Arrays

17

• An array cannot contain data of different types correctly!

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

(41)

### Example

18

1 >> stock = {"TSMC", 100;

2 "GOOG", 200;

3 "AAPL", 300}

4

5 stock =

6

7 3x2 cell array

8

9 {"TSMC"} {[100]}

10 {"GOOG"} {[200]}

11 {"AAPL"} {[300]}

• However, the arithmetic operators cannot be applied to the cell arrays!

(42)

### Referring to Cell Arrays

• Using curly braces, {·} will reference the contents of a cell.

1 >> A{3, 1}

2

3 ans =

4

5 AAPL

• More details can be found in here.

(43)

1 >> [mat, txt, raw] = xlsread("2330.xlsx")

2 >> [~, ~, raw] = xlsread("2330.xlsx")

• By default, it returns a numeric matrix.

• The text part is the 2nd output, separated from the numeric part.

• You may consider the whole spreadsheet by using the 3rd output (stored in a cell array).

• Note that you can use ∼ to drop the output value.

(44)

### Summary

19,20

• Square brackets [·]: only used in array operations.

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

• Curly brackets {·}: only used in cells.

e.g. A = {’MATLAB’, numbers}.

• Parentheses (·).

Arithmetic, e.g. (x + y )/z.

Input arguments of functions, e.g. sin(pi / 2), exp(1).

Array addressing, e.g. A(1) refers to the first element in array A.

(45)

### More Data Structures

• See https://www.mathworks.com/help/matlab/

data-types_data-types.html.21

(46)

### Vectorization

22

• MATLAB favors array operations.

• When two arrays have the same dimensions, addition, subtraction, multiplication, and division apply on an element-by-element basis.

• For example,

1 >> x = [1, 2, 3];

2 >> y = [4, 5, 6];

3 >> x + y

4

5 ans =

6

7 5 7 9

(47)

### Element-By-Element Operations

• The left division is used in the inverse matrix problems.23

(48)

### Relational Operators

24

• Note that relational operators make comparisons between two

(49)

### Logical Values

• For example,

1 >> x = 1; y = 2;

2 >> x == y

3

4 ans =

5

6 0

• In general, the numeric number 0 is regarded as false while 1 (even any nonzero number) is regarded as true.

• The function true and false represent logical true and false, respectively.25

(50)

### Filtering

• Logical arrays are often used as masks (or filters) to manipulate arrays.

1 >> scores = { "Arthur", 50;

2 "Bob", 60;

3 "Cynthia", 70};

4 >> mask = [scores{:, 2}] >= 60

5

7

8 0 1 1

9

11

12 ans =

Keratinizing squamous cell carcinoma composed of recognizable squamous tumor cells with pronounced keratinization (B) (original magnification ×200).6. Dark blue punctate (dotlike,

Extranodal natural killer/T cell (NK/T cell) lymphoma, nasal type, is a rare non-Hodgkin lymphoma originating in the nasal cavity or in the paranasal sinuses.. It is strongly

A particular type of DL based on convolutional neural networks (CNNs) has shown wide applicability on imaging data, as it can be used to extract a wide array of features by

Shorter pulses allow cells to be analyzed with high accuracy Shorter pulses allow cells to be analyzed with high accuracy... Cuvette Flow Cell – Coulter ALTRA and

• The memory storage unit holds instructions and data for a running program.. • A bus is a group of wires that transfer data from one part to another (data,

In this class, we will learn Matlab and some algorithms which are the core of programming world. Zheng-Liang Lu 26

Laser Capture Microdissection Microdissection of Fluorescently of Fluorescently Labeled Embryonic Cranial Neural Crest Cells Labeled Embryonic Cranial Neural Crest Cells..

 A genre is more dynamic than a text type and is always changing and evolving; however, for our practical purposes here, we can take genre to mean text type. Materials developed