introduction to matlab programming with applicationsd00922011/matlab/272/20160808.pdf ·...

61
Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer Science and Information Engineering National Taiwan University Matlab 272 Summer 2016

Upload: lyliem

Post on 16-Apr-2018

253 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Introduction to Matlab Programming withApplications

Zheng-Liang Lu

Department of Computer Science and Information EngineeringNational Taiwan University

Matlab 272Summer 2016

Page 2: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Class Information

• The course page ishttp://www.csie.ntu.edu.tw/˜d00922011/matlab272.html.

• Lecture notes will be uploaded right before class.

• Note that the lecture notes are organized in English.

• You can contact me by the following approaches:• [email protected] (for technical support only)• Facebook

Zheng-Liang Lu 1 / 60

Page 3: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Prerequisites

• No programming experience required.• It would be helpful if you have some.

• Linear algebra is strongly recommended.• A beautiful and complete theory, widely used in numerical

methods.• Matlab refers to “Matrix laboratory.”

• I promise to keep everything simple in this class.1

• You should consider other classes if you want to learnadvanced courses in computer science.

1“Simple is not easy. . . . Easy is a minimum amount of effort to produce aresult. . . . Simple is very hard. Simple is the removal of everything except whatmatters. . . .” See here.

Zheng-Liang Lu 2 / 60

Page 4: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Grading

• To acquire the certificate, you need at least 70 pts in theend of class.

• In-class exercises (0 pts)• Final project/exam (100 pts)

Zheng-Liang Lu 3 / 60

Page 5: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Final Project

• Topic: no restriction.

• Requirement: Matlab is the main programming language.

• Your grade depends on the following aspects:• Problem definition• Innovation2

• Completion

• Goal• To solve a problem by formulating the problem, organizing an

algorithm, writing codes• To get familiar with programming concepts• To expand your horizon by asking questions in others’ work

2No copy-and-paste. You should understand the program thoroughly.Zheng-Liang Lu 4 / 60

Page 6: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Final Exam

• On-site programming

• 8 to 10 questions

• Open everything3

3You should learn how to integrate the tools you use, even if the tools youhave are not made on your own.

Zheng-Liang Lu 5 / 60

Page 7: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Roll Call

Zheng-Liang Lu 6 / 60

Page 8: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Before we start, you should ask yourself...

• Why do you learn how to program?• Read http://buzzorange.com/techorange/2016/01/04/

how-to-image-programming-edu/.

• Why do you choose Matlab?• If you choose Matlab, then I assume that you are working on

numerical problems.• So math, math, and math.• Math could be difficult.• I will try my best to convince you that, math is simple.

Zheng-Liang Lu 7 / 60

Page 9: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

“In fact, researchers have settled on what they believe isthe magic number for true expertise: ten thousandhours.”

– Malcolm Gladwell, Outliers: The Story of Success

“Learning a new language is harmless. It gives you newideas and insights.”

– Yukihiro Matsumoto (松本行弘) (1965-)

Zheng-Liang Lu 8 / 60

Page 10: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

What Is Programming?

• Programming is the activity of writing a sequence ofinstructions to tell a machine to perform a specific task.

• A sequence of instructions → program• A set of well-defined notations is used to write a program →

programming language• The person who writes a program → programmer designer4

4Writing codes is not what the CS people work for. We are writing codes tomake a better world.

Zheng-Liang Lu 9 / 60

Page 11: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

In Practice

• Programming is to provide a solution to a real-world problemusing computational models supported by programminglanguages.

• The solution is a program.• The program must be effective.5

5For example, time is money.Zheng-Liang Lu 10 / 60

Page 12: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Programs

• A program is a sequence of instructions, written in an artificiallanguage, to perform a specified task with a machine.

• They are almost everywhere.

• For example,• Computer virus• Video games• Operating systems6

• ATM, traffic light, Google search engine, recommendationsystem...

• Differences: goal, functionality, algorithms, and resources.

6For desktops and laptops, you may know Windows, Unix, Linux, and MacOS. For mobile devices, Windows, Android, and iOS are pupolar.

Zheng-Liang Lu 11 / 60

Page 13: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

How and Where The Programs Run9

• The programs are activated from the disk into the mainmemory.

• Now we call them the processes.7

• CPUs contain the arithmetic and logic unit (ALU) and theregisters.

• ALU is responsible for the computational power.• Registers store the data to be used temporarily.8

• The outputs are written back to the main memory and furtherstored into the disk if necessary.

7The “process” is a formal terminology used in OS.8Limited number of registers.9You may refer to any class for an introduction to computer system. For

example, Introduction to Computer Science & Programming in C.Zheng-Liang Lu 12 / 60

Page 14: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Memory Hierarchy10

10See Figure 1-9 in Bryant, p. 14.Zheng-Liang Lu 13 / 60

Page 15: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Programming Languages

• A programming language is an artificial language tocommunicate with machines.

• Recall how you learned the 2nd nature language when youwere a kid.

• Programming languages → syntax and semantics• Used to express algorithms• Used to control the behavior of machines

• How many programming languages in the world?• More than 1000.• Top 20 programming languages can be found in TIOBE.• Matlab: 15th

• Note that every language originates from reasons.

Zheng-Liang Lu 14 / 60

Page 16: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

History

• Matlab belongs to the post 3rd-generation programminglanguages.11

• 1st generation: machine code• 2nd generation: assembly code• 3rd generation: high-level programming languages• Post-3rd generations

11Wikipedia reports that Matlab is one of 4-th programming languages.Zheng-Liang Lu 15 / 60

Page 17: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Zheng-Liang Lu 16 / 60

Page 18: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

1st-Generation Programming Languages

• Computers understand instructions only in binary, which is asequence of 0s and 1s. (Why?)

• Each computer has its own set of instructions.12

• So the programs at the very early stage weremachine-dependent.

• These are so-called the machine language, aka machine code.

• Pros:• Most efficient for machines

• Cons:• Hard to program for human• Not portable

• Still widely used in programming lower level functions of thesystem, such as drivers, interfaces with firmware and hardware.

12For example, X86 and ARM.Zheng-Liang Lu 17 / 60

Page 19: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

2nd-Generation Programming Languages

• An assembly language uses mnemonics13 to representinstructions as opposed to the machine codes.

• Hence, the code can be read and written by humanprogrammers.

• Yet, it is still machine-dependent.

• To run on a computer, it must be converted into a machinereadable form, a process called assembly.

Zheng-Liang Lu 18 / 60

Page 20: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

• More often find use in extremely intensive processing such asgames, video editing, graphic manipulation/rendering.

• Note that machine languages and assembly languages are alsoknown as low-level languages.

13Easy to recognize and memorize.Zheng-Liang Lu 19 / 60

Page 21: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

3rd-Generation Programming Languages

• The high-level programming languages use English-like words,mathematical notation, and punctuation to write programs.

• They are closer to the human languages.

• Pros:• Portable, machine-independent• Human-friendly

• For example, C14, C++15, and Java16.

14Dennis Ritchie (1973)15Bjarne Stroustrup (1983)16James Gosling (1995)

Zheng-Liang Lu 20 / 60

Page 22: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

• Note that the machines understand and execute only themachine codes as before.

• The translation is accomplished by a compiler, an interpreter,or a combination of both.17

17If you’ve learned C, you should take a look at the design of compiler.Zheng-Liang Lu 21 / 60

Page 23: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

What Can A Program Do?

• A program is an implementation of an algorithm expressed ina specific programming language.

Zheng-Liang Lu 22 / 60

Page 24: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Algorithms In A Nutshell

• An algorithm is a well-defined computational procedure thattakes a set of values as input and produces a set of values asoutput.

• Simply put, an algorithm is a procedure that solves aparticular class of problems, such as a cookbook.

Zheng-Liang Lu 23 / 60

Page 25: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Properties of Algorithms19

• An algorithm must possess the following properties18:• Input and output• Correctness• Definiteness: basic instructions provided by a machine, e.g.

+−×÷.• Effectiveness: action which can be completed by combination

of basic instructions.• Finiteness: resource requirement, especially time and space.

• Note that an algorithm is not necessarily expressed in aspecific programming language.

• Could use human languages, graphs, and pseudo codes.

18Alan Turing (1912–1954)19Donald E. Knuth (1938–)

Zheng-Liang Lu 24 / 60

Page 26: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Example

• Organize an algorithm that finds the greatest element in theinput list, say A.

Input: A (a list of n numbers)Output: max (the greatest element in A)

• Can you provide a procedure to determine the greatestelement? For all situations?

Zheng-Liang Lu 25 / 60

Page 27: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

My Solution

• The first element of A can be fetched by calling A(1).

• Let ← be the assignment operator in the following pseudocode.

1 max <- A(1)2 for i <- 2 ~ n3 if A(i) > max4 max <- A(i)5 end6 end7 return max

• How to find the minimal element?

• How to find the location of the greatest element?

• Why not max ← 0?

Zheng-Liang Lu 26 / 60

Page 28: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

“Computers are good at following instructions, but not atreading your mind.”

– Donald Knuth (1938-)

“Computer science is no more about computers thanastronomy is about telescopes.”

– Edsger Wybe Dijkstra (1930-2002)

“There are two ways of constructing a software design:One way is to make it so simple that there are obviouslyno deficiencies, and the other way is to make it socomplicated that there are no obvious deficiencies. Thefirst method is far more difficult.”

– Tony Hoare (1934-)

Zheng-Liang Lu 27 / 60

Page 29: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Alan Turing (1912–1954)

• Provided a formalization of the concepts of algorithm anduniversal computation model which can be considered amodel of a general purpose computer.

• Turing machine: a central object of study in theory ofcomputation

• Toy example from Google• Also proved that the halting problem for Turing machines is

undecidable.20

• Turing Test: an attempt to define a standard for the so-called“intelligent” machines

• The father of computing theory and artificial intelligence (AI)

• Turing Award of ACM21

• The Imitation Game (2014)

20That is, there exist problems which are not solvable.21Association for Computing Machinery

Zheng-Liang Lu 28 / 60

Page 30: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Alan Turing

Zheng-Liang Lu 29 / 60

Page 31: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

What is Matlab?

• Matlab is a powerful and easy-to-use integrated programmingenvironment, especially for numerical purposes.

• programmable, matrix computation, fruitful toolboxes22

available, good memory management, easy to draw a graph...

• The only thing you need to provide is ...

22http://www.mathworks.com/products/

Zheng-Liang Lu 30 / 60

Page 32: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Algorithms!23

23A screenshot of The Social Network (2010)Zheng-Liang Lu 31 / 60

Page 33: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Conclusions

• Program design ≈ algorithm + programming language• Algorithm ← idea, procedure, steps, SOP• Programming language ← Chinese, English

• In this class, we will learn Matlab and some classicalalgorithms.

• Wish you could pick up the essentials of programming.

Zheng-Liang Lu 32 / 60

Page 34: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Fathers of Matlab24

Prof. Cleve Moler

241989Zheng-Liang Lu 33 / 60

Page 35: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Jack Little

Zheng-Liang Lu 34 / 60

Page 36: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Get started to

implement your idea with

Matlab.

Zheng-Liang Lu 35 / 60

Page 37: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

1 >> Lecture 12 >>3 >> -- Overview4 >>

Zheng-Liang Lu 36 / 60

Page 38: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Working Environment

Zheng-Liang Lu 37 / 60

Page 39: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Command Window

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

1 >> disp('Hello, Matlab.');

• disp prints the string as input in the parenthesis.• A string is single-quoted in Matlab.

• Convention in the slides:• Boxes are the listings for sample programs.• Words and sentences highlighted in red are important.• Words in blue are reserved words.• Bold words in black are functions.

Zheng-Liang Lu 38 / 60

Page 40: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Help Yourself

• Don’t be frustrated by these red lines.• Matlab interrupts your program if there is a syntax error.• These errors are easier than logical errors, which cannot be

found by the machine itself!

• The function help followed by the command you want to usereturns the document of that command, for example,

1 >> help disp2 ...

• Also, the help browser provides detail of commands withexamples.

• Moreover, Google is your best friend (when you learn byyourself).

Zheng-Liang Lu 39 / 60

Page 41: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

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

– Alfred Pennyworth, Batman Begins (2005)

Zheng-Liang Lu 40 / 60

Page 42: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Script Editor

• We often write a program in the script editor and save theprogram into an m file.

• These m files can be scripts and functions.• A script is a complete program which contains the input data

and can be executed directly.• A function is a program which may need input data when

being called in other programs. (why?)

Zheng-Liang Lu 41 / 60

Page 43: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Zheng-Liang Lu 42 / 60

Page 44: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Debut

1 % This is my first Matlab program.2 clear; % Clear all variables stored in Workspace.3 clc; % Clear the screen.4 % main program5 disp('Hello, world.');

• The lines which begins with % are regarded as the comments.

• Comments are not executed.

• The function clear is used to release all the variables in theworkspace.25

• The function clc cleans the command window.

25You may release the variable x by calling clear x .Zheng-Liang Lu 43 / 60

Page 45: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

• Save26 and click Run.27

• Do not give a script file the same name as a variable. (Why?)

• If the m file to run is not at the current folder when youexecute it, Matlab will offer two options:

1. Change folder2. Add to Path Pool28

• You can run helloworld.m later just by directly callinghelloworld in the command window.

1 >> helloworld2

3 Hello, world.

26Simply press ctrl + s.27Alternatively, press F5 for saving the file and running the program.28Path Pool is a list of directories where the programs could be.

Zheng-Liang Lu 44 / 60

Page 46: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Comments In Program

• Anything following a % is regarded as a comment.29

• Press ctrl + r to comment lines.• Press ctrl + t to de-comment lines which begin with %.• Or use %{ · · · %} to comment a block of lines.

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

1 >> help helloworld2

3 This is my first Matlab program.

• Why documents?• Helpful for both the programmers and users.• Avoid wasting time later.

29Not be executed.Zheng-Liang Lu 45 / 60

Page 47: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Variables

• A variable is used to store a value or values.• Just like a box.

• In the computer languages, the statement is normally like:

var = expression,

where var is a variable and expression is any arithmeticoperation.30

• For example, suppose x = 0.• Then run y = x + 1 and so y = 1. (Trivial.)

• How about x = x + 1?• Actually, the assignment operator (=) is defined to assign a

value to the variable, from right to left.

30In most languages, 1 = x is not allowed. (Why?)Zheng-Liang Lu 46 / 60

Page 48: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

• For example,

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

5 ans =6

7 30

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

• If you drop the semicolon (;) in the line, then the immediateresult will appear in the command window.

Zheng-Liang Lu 47 / 60

Page 49: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

1 >> a = 102

3 a =4

5 10

• Note that you may not drop semicolons in other programminglanguages.31

• 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

31For example, the semicolon is used as the end symbol of a statement in C,C++, and Java.

Zheng-Liang Lu 48 / 60

Page 50: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

• Matlab is case-sensitive, e.g. A and a.

• The length of name is limited to 63 characters.32

• The function namelengthmax returns the maximum length inthis machine.

• We avoid to use names of reserved words33 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 mnemonic.34

32Windows 7 (64-bit) in this case33Try iskeyword.34To assist your memory.

Zheng-Liang Lu 49 / 60

Page 51: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Data Types

• Binary digit, aka bit, is a digit whose value is either 0 or 1.

• Everything is encoded in binary.• How many bits do you need to store a zero in the memory?

• Different types of variables occupy different size of memory.35

• So the types determine the possible states.• Consider 2 bits.• There are 22 = 4 possible states which can be represented by 2

bits.

• Particularly, integers and real numbers (more precisely,floating points36) are different types.

• An int value takes 32 bits in memory.• A double value takes 64 bits.37

35Use class(x) to check the data type of x .36See IEEE 754 Standard (1985).37The type double refers to “double precision floating point.”

Zheng-Liang Lu 50 / 60

Page 52: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Computational Limits

• It is a common convention to use e to identify a power of 10,e.g. 1e5 = 100, 000 and −1.2e − 5 = −0.000012.

Zheng-Liang Lu 51 / 60

Page 53: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Floating Points and Numerical Error

• All numeric variables are stored as the type double by default.

• Floating point is the formulaic representation thatapproximates a real number.38

• Try 0.5− 0.1− 0.1− 0.1− 0.1− 0.1 =? (Why?)

• Numerical error is the combined effect of two kinds of error ina calculation:

• caused by the finite precision of computations involvingfloating-points, as the above example;

• caused by the truncation because simplifications are made tothe mathematical equations to make them more amenable tocalculation, e.g. the truncation to a infinite series.

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

38See https://en.wikipedia.org/wiki/Floating_point.Zheng-Liang Lu 52 / 60

Page 54: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Scalar Variables

• A scalar is a single number.

• A scalar variable is a variable that contains a single value.

• 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

numbersa + bi ,

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

• Try x = 1 + i in the command window.

• Usually used for parameters of the problems.

• For example, pi is a default variable to store the ratio of acircle’s circumference to its diameter.

39In math, C1 is equivalent to R2. So x contains two double values.Zheng-Liang Lu 53 / 60

Page 55: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Scalar Arithmetic Operators40

40See Table 2.1 Arithmetic Operations Between Two Scalars in Moore, p. 21.Zheng-Liang Lu 54 / 60

Page 56: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Display Format41

• Note that the data is displayed in the specified way withoutchanging the value of data.

41See Table 1.1-5 Numeric display formats in Palm, p. 15.Zheng-Liang Lu 55 / 60

Page 57: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Arrays

• An array, is a data structure consisting of a collection ofelements, each identified by at least one array index.

• In math, it could be• 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.

• Actually, vectors can be regarded as 1D arrays.

Zheng-Liang Lu 56 / 60

Page 58: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Example

1 >> rowVector = [1 2 3] % [ ... ] is used in arrays2

3 rowVector =4

5 1 2 36

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

8

9 columnVector =10

11 112 213 314

15

16

Zheng-Liang Lu 57 / 60

Page 59: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

17

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

20 matrix =21

22 1 2 323 4 5 624 7 8 9

• 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, a 104 × 104 matrix takes 762.94 MB in memoryspace.42

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

42108 × 8 / 220 = 762.94 MBZheng-Liang Lu 58 / 60

Page 60: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

Referring to Matrix Elements43

• Subscripted indexing

• Linear indexing: column major order.

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

3 ans =4

5 66

7 >> matrix(8) % using linear indexing8

9 ans =10

11 6

43Note that the first element of the array starts from 1 not 0 if you haveprogramming experiences in C/C++/Java.

Zheng-Liang Lu 59 / 60

Page 61: Introduction to Matlab Programming with Applicationsd00922011/matlab/272/20160808.pdf · Introduction to Matlab Programming with Applications Zheng-Liang Lu Department of Computer

More Tricks

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

3 ans =4

5 4 66

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

9 matrix =10

11 2 312 5 613 8 914

15 >> matrix = [[1; 4; 7] matrix] % Try.

Zheng-Liang Lu 60 / 60