INTRODUCTION TO MATLAB ............................... 10

waisttherapeuticΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 11 μήνες)

154 εμφανίσεις

MATLAB: Prog. & Prob. Solving

p.
1

2001 Notes

INTRODUCTION TO MATL
AB

...............................

10

W
HAT IS
M
ATLAB
?

................................
.....................

11

H
ISTORY OF
M
ATLAB

................................
..................

12

A
N
I
NITIAL
E
XAMPLE

................................
..................

13

Population Growth

................................
.................

13

S
OME
F
EATURES

................................
.........................

16

R
UNNING
M
ATLAB

................................
......................

17

Startup Under Unix

................................
.................

17

Startup Under Windows 95/98

................................

17

To Exit

................................
................................
....

17

H
ELP
&

D
EMOS

................................
...........................

18

Through the Command Window

.............................

18

Through the Help Window

................................
......

18

Through the Help Desk

................................
...........

18

Demonstrations

................................
.......................

18

C
ONTROLLING THE
E
NVIRONMENT

.............................

20

A

2
ND

E
XAMPLE

................................
...........................

21

Final Approach

................................
.......................

21

M
AP
G
ENERATION

................................
......................

23

M
AP
S
MOOTHING

................................
........................

24

M
AP
C
ODE

................................
................................
..

25

mapGen

................................
................................
...

25

MapPlateau

................................
............................

26

P
RINCIPLES OF
“G
OOD


P
ROGRAMS

...........................

28

R
EVIEW

................................
................................
.......

29

MATLAB SYNTAX

................................
.....................

30

S
OME
S
IMPLE
C
ALCULATIONS

................................
....

31

B
ASIC
M
ATHEMATICAL
O
PERATORS

...........................

32

E
XPRESSIONS

................................
..............................

33

V
ARIABLES
&

A
SSIGNMENT

................................
........

34

T
HE
ANS

VARIABLE

................................
......................

35

Examining a Variable’sValue

................................
.

35

MATLAB: Prog. & Prob. Solving

p.
2

2001 Notes

S
EMICOLON
,

C
OMMA
&

P
ERIOD

................................
..

37

Semicolon
................................
................................

37

Comma

................................
................................
....

37

Period

................................
................................
.....

37

L
AYOUT
C
ONVENTIONS

................................
..............

39

C
OMMENTS

................................
................................
.

40

U
SING
C
OMMENTS

................................
......................

41

C
OMMENTS
&

M
ATLAB
H
ELP

................................
.....

42

S
OME USEFUL
M
ATHEMATICAL
F
UNCTIONS
................

44

S
CRIPT
M
-
F
ILES

................................
..........................

46

Basic Approach using M
-
Files

................................

46

Naming

................................
................................
...

46

M
ATLAB
N
AME
S
PACE

................................
................

48

Matlab Search Path

................................
................

48

R
EVIEW

................................
................................
.......

50

MATLAB VARIABLES & D
ATA TYPES

................

51

V
ARIABLES
................................
................................
..

52

I
DENTIFIERS

................................
................................

53

M
EANINGFUL
I
DENTIFIERS

................................
..........

54

Some Examples

................................
.......................

54

W
EAK
T
YPING

................................
.............................

55

I
MPLICATIONS OF
W
EAK
T
YPING

................................

56

Advantages

................................
..............................

56

Disadvantages

................................
........................

56

S
PECIAL
(B
UILT
-
IN
)

C
ONSTANTS
&

V
ARIABLES
..........

57

C
OMPLEX
N
UMBERS

................................
...................

58

N
AN
&

INF

................................
................................
...

59

S
TRINGS

................................
................................
......

61

M
ANAGING
V
ARIABLES

................................
..............

63

clear

................................
................................
........

63

M
ANAGING
W
ORKSPACE
:

LOAD

................................
..

64

M
ANAGING
W
ORKSPACE
:

SAVE

................................
..

65

R
EVIEW

................................
................................
.......

66

MATLAB: Prog. & Prob. Solving

p.
3

2001 Notes

I/O IN MATLAB

................................
..........................

67

B
ASIC
I
NPUT

................................
................................

68

The Input Statement

................................
................

68

I
NPUTTING
S
TRINGS

................................
....................

69

B
EHAVIOUR OF

I
NPUT
S
TATEMENT

.............................

70

M
ICRO
:

A
MOEBA
E
XPANSION

................................
.....

71

M
ICRO
R
UN

................................
................................
.

72

B
ASI
C
O
UTPUT

................................
............................

73

The disp Statement

................................
..................

73

T
HE FORMAT COMMAND

................................
.............

74

F
ORMAT
E
XAMPLES

................................
....................

75

MORE

................................
................................
...........

77

F
ILES IN
G
ENERAL

................................
.......................

78

Opening & Closing Files

................................
........

78

FPRINTF

................................
................................
.......

80

C
ONTROLLING FPRINTF

................................
...............

82

FSCANF

................................
................................
........

83

P
ROJECTILE
E
XAMPLE

................................
.................

84

P
ROJECTILE
C
ODE

................................
.......................

85

P
ROJECTILE
R
UN

................................
.........................

88

P
ROJECTILE
P
LOT

................................
........................

89

R
EVIEW

................................
................................
.......

90

ARRAYS IN MATLAB 1


VECTORS

......................

91

M
OTIVATION

................................
...............................

92

V
ISUALISING A
1D

A
RRAY
(V
ECTOR
)

.........................

93

M
ATLAB
&

A
RRAYS

................................
....................

94

V
ECTOR
C
REATION

................................
.....................

96

V
ECTOR
C
REATION
E
XAMPLE

................................
.....

98

A
DDRESSING THE
E
LEMENTS OF A
V
ECTOR

..............

100

C
OLUMN VS
.

R
OW
V
ECTORS

................................
.....

102

C
OLUMN VS
R
OW
E
XAMPLE

................................
......

103

S
CALAR
-
A
RRAY
M
ATHEMATICS

...............................

104

MATLAB: Prog. & Prob. Solving

p.
4

2001 Notes

E
XAMPLE CEL
2
FAR
.
M

................................
................

106

CEL
2
FAR
R
UN

................................
............................

107

A
RRAY
-
A
RRAY
M
A
THEMATICS

................................

108

E
XAMPLE


BOUNCING
.
M

................................
..........

110

BOUNCING
.
M
C
ODE

................................
...................

111

R
EVIEW

................................
................................
.....

113

MATLAB ARRAYS 2


MATRICES

.......................

114

2D(+)

A
RRAYS


M
OTIVATION

................................
.

115

V
IS
UALISING
2D

A
RRAYS

................................
.........

116

V
ISUALISING
2D

A
RRAYS
E
XAMPLE

.........................

117

C
REATION

................................
................................
.

118

C
REATION
E
XAMPLE

................................
.................

119

M
ATHEMATICS OF
M
ATRICES

................................
...

120

M
ATHEMATICS
E
XAMPLE

................................
..........

1
21

A
DDRESSING
&

M
ANIPULATION

...............................

125

A
DDRESSING
&

M
ANIPULATION
E
XAMPLE

...............

126

E
XAMPLE


N
ETWORK
T
RAFFIC

................................

129

T
RAFFIC
C
ODE

................................
..........................

130

T
RAFFIC
E
XAMPLE
P
LOTS

................................
.........

133

S
PECIAL
M
ATRICES

................................
...................

134

S
PECIAL
M
ATRICES
E
XAMPLE

................................
...

135

A
RRAY
S
IZES
................................
.............................

136

A
RRAY
S
IZES
E
XAMPLE

................................
............

138

M
ULTI
-
DIMENSIONAL
A
RRAYS
................................
..

139

L
INEAR
E
QUATIONS

................................
..................

140

L
INEAR
E
QUATIONS
E
XAMPLE

................................
..

141

R
EVIEW

................................
................................
.....

142

MATLAB RELATIONAL OP
ERATORS & BASES

................................
................................
......................

143

M
OTIVATION
-

R
ELATIONAL
O
PERATORS

.................

144

B
OOLEAN
O
PERATIONS

................................
.............

145

E
XAMPLE


P
IECEWISE
F
UNCTIONS

...........................

149

MATLAB: Prog. & Prob. Solving

p.
5

2001 Notes

P
IECEWISE
F
UNCTION
E
XAMPLE

...............................

150

N
A
N

&

E
MPTY
A
RRAYS

................................
............

152

B
ASE
C
ONVERSION

................................
...................

154

B
ASE
C
ONVERSION
E
XAMPLE

................................
...

156

B
IT
L
EVEL
O
PERATIONS

................................
............

157

R
EVIEW

................................
................................
.....

158

MATLAB SELECTION STA
TEMENTS (IF &
SWITCH)

................................
................................
....

159

M
OTIVATION

................................
.............................

160

S
IMPLE
IF

................................
................................
..

162

E
XAMPLES


S
IMPLE
IF

................................
.............

163

IF
-
ELSE

................................
................................
....

164

E
XAMPLE


IF
-
ELSE

................................
.................

165

IF
-
ELSEIF
-


................................
...........................

166

E
XAMPLE


IF
-
ELSEIF…

................................
.........

168

T
RUTH
T
ABLES
&

C
OMPOUND
IF
S

............................

169

SWITCH

................................
................................
...

172

E
XAMPLE

S
WITCH

................................
...................

174

R
EVIEW

................................
................................
.....

175

LOOPS IN MATLAB

................................
.................

176

M
OTIVATION

................................
.............................

177

D
EFINITE
I
TERATION
(FOR

L
OOP
)

............................

178

FOR

L
OOP
S
CHEMATIC

................................
.............

179

FOR

L
OOP
E
XAMPLE

................................
................

180

FOR

L
OOP
A
DDITIONAL
................................
............

182

I
NDEFINITE
I
TERATION
(WHILE

L
OOP
)

....................

183

WHILE

L
OOP
S
CHEMATIC

................................
........

184

WHILE

L
OOP
E
XAMPLES

................................
..........

185

WHILE

VS
IF

................................
............................

187

G
ENERAL
L
OOPS
&

BREAK

................................
.....

188

B
REAK
S
CHEMATIC

................................
...................

189

C
OMBINED
(M
AJOR
)

E
XAMPLE

................................
.

191

MATLAB: Prog. & Prob. Solving

p.
6

2001 Notes

W
ORMS
R
UN

................................
.............................

195

L
OOP
U
SAGE
G
UIDELINES

................................
.........

196

L
OOP
C
ONTROL

................................
.........................

197

C
OMMON
T
YPES OF
L
OOPS

................................
........

198

L
OOPS VS
I
MPLICIT
V
ECTORISA
TION

.........................

200

L
OOPS VS
.

V
ECTOR
E
XAMPLE

................................
...

201

R
EVIEW

................................
................................
.....

202

EFFICIENCY & ER
RORS

................................
........

203

M
OTIVATION

................................
.............................

204

N
UMERIC
L
IMITATIONS

................................
.............

205

Overflow

................................
...............................

205

Underflow

................................
.............................

206

R
OUNDING
&

C
ANCELLATION

................................
...

207

Rounding (Precision)

................................
............

207

Cancelation (Order of Precedence)

......................

207

W
ORK
-
A
ROUNDS FOR
N
UMERIC
L
IMITATIONS

.........

209

For Instance: Comparing Two Numbers

..............

209

E
RRORS
&

D
EBUGGING IN
M
ATLAB

..........................

211

M
ATLAB
D
EBUGGER

................................
.................

212

O
RDER OF AN
A
LGORITHM

................................
........

213

T
IMING IN
M
ATLAB

................................
...................

215

P
ERFORMANCE
P
ROFILING IN
M
ATLAB

.....................

216

P
ROFILER
E
XAMPLE

................................
..................

217

G
UIDELINES FOR
E
FFICIENCY

................................
....

218

Special Cases
and Redundant Checking

...............

218

E
FFICIENCY
:

R
EDUNDANCY
&

F
UNCTIONS

...............

220

Avoid Redundant Computations
............................

220

Minimise Costly Function Usage

..........................

220

E
FFICIENCY
:

A
RRAYS

................................
................

222

Minimise Array Referencing

................................
.

222

Time vs Space

................................
.......................

222

E
FFICIENCY
:

L
OOP
T
ERMINATION

.............................

224

MATLAB: Prog. & Prob. Solving

p.
7

2001 Notes

Avoid Late Termin
ation of Loops (Needless
Calculations)

................................
........................

224

E
FFICIENCY


C
OMPLICATING
I
SSUES

.......................

225

L
OOPING VS
I
MPLICIT
V
ECTORISATION

.....................

226

T
IMING
E
XAMPLE

................................
......................

227

S
HELL
1



L
OOPING WITHOUT
E
FFICIENCY

................

22
8

S
HELL
2



L
OOPIN
G
E
FFICIENTLY

..............................

229

S
HELL
3



I
MPLICIT
V
ECTORISATION

.........................

231

R
EVIEW

................................
................................
.....

232

BASICS OF MATLAB FUN
CTIONS

.......................

233

M
OTIVATION

................................
.............................

234

C
ALLING
F
UNCTIONS

................................
................

235

O
VERVIEW OF
F
UNCTION
C
ALL
&

R
ETURN
P
ROCESS

237

O
N
M
ATLAB
'
S
I
N
-
B
UILT
F
UNCTIONS

.........................

238

W
HAT
M
AKES A
G
OOD
F
UNCTION


S
OFTWARE
E
NG
INEERING
P
RINCIPLES

................................
.........

239

F
UNCTION
D
ECLARATION
S
YNTAX

...........................

240

A

F
IRST
F
UNCTION

................................
....................

241

E
XAMPLE
:

T
IMING OF
F
UNCTIONS

.............................

242

C
OMMENTS
&

F
UNCTIONS

................................
........

244

T
OP
-
D
OWN
V
IEW OF
F
UNCTION
D
ESIGN

...................

245

B
OTTOM
-
U
P
V
IEW OF
F
UNCTIONS

............................

246

T
HE
B
LACK
B
OX
P
ARADIGM

................................
.....

247

P
ARAMETERS


I
NPUT
C
HANNE
L

...............................

248

R
ETURNED
V
ALUES


O
UTPUT
C
HANNEL

.................

249

E
XAMPLE


D
ESCRIPTION

................................
..........

250

E
XAMPLE
R
ESULTS

................................
...................

251

E
XAMPLE


DAILY
T
EMPS

................................
..........

252

E
XAMPLE


GET
T
EMPS

................................
..............

253

E
XAMPLE


PROCESS
T
EMPS

................................
......

254

E
XAMPLE


TEMP
T
ABLE

................................
............

256

E
XAMPLE


TEMP
P
LOT

................................
..............

258

R
EVIEW

................................
................................
.....

259

MATLAB: Prog. & Prob. Solving

p.
8

2001 Notes

FURTHER MATLAB FUNCT
IONS

........................

260

F
ORMAL VS
.

A
CTUAL
P
ARAMETERS
&

O
UTPUTS

......

261

P
ARAMETER
A
SSOCIATION

................................
........

262

P
ARAMETER
A
SSOCIATION
E
XAMPLE

.......................

263

P
ASS BY
V
ALUE
&

P
ASS BY
R
EFERE
NCE

...................

265

P
ASS BY
V
ALUE
E
XAMPLE

................................
........

266

S
COPE
R
ULES
&

W
ORKSPACES

................................
.

267

S
COPE
E
XAMPLE

................................
.......................

268

R
UN
-
T
IME
S
TRUCTURE
&

THE
S
TACK

.......................

270

R
ETURN
,

E
RROR
&

W
ARNING

................................
...

272

NARGIN
&

V
ARIABLE
I
NPUTS

................................
....

274

NARGOUT
&

V
ARIABLE
O
UTPUTS

.............................

275

NARGIN
&

NARGOUT
E
XAMPLE

................................
.

276

G
LOBAL
V
ARIABLES

................................
.................

281

E
FFICIENCY
I
SSUES

................................
...................

282

VARARGIN
&

VARARGOUT
................................
.........

283

S
UB
-
FUNCTIONS

................................
........................

284

R
EVIEW

................................
................................
.....

285

GRAPHICS & OTHER MAT
LAB FEATURES

.....

286

M
OTIVATION

................................
.............................

287

2D

G
RAPHICS

PLOT

................................
.................

288

A
XES
&

L
ABELS

................................
........................

290

P
RINTING
F
IGURES

................................
....................

291

M
ULTIPLE
F
IGURES
&

SUB
-
PLOTS

.............................

293

O
THER
2D

PLOTS

................................
.......................

294

M
ULTIPLE
P
LOTS
E
XAMPLE

................................
......

295

2D

P
LOTS
-

O
UTPUT

................................
..................

298

A
DDING TEXT

................................
............................

300

3D

G
RAPHICS


L
INE

................................
.................

301

3D

G
RAPHICS


S
URFACE

................................
..........

302

3D

S
URFACES
E
XAMPLE

................................
...........

303

P
OLYNOMIALS

................................
...........................

304

MATLAB: Prog. & Prob. Solving

p.
9

2001 Notes

I
NTERPOLATION
&

S
PLINES

................................
.......

306

O
PTIMISATION

................................
...........................

308

I
NTEGRATION
,

D
IFFERENTIATION
&

O
RDINARY
D
IFFERENTIAL
E
QUATIONS

................................
.......

309

D
ATA
-
STRUCTURES

................................
...................

310

O
BJECT
O
RIENTED

................................
....................

312

GUI

D
ESIGN

................................
..............................

313

T
OOLBOXES

................................
...............................

314

R
E
VIEW

................................
................................
.....

315

3D MAPS IN MATLAB, A

CASE STUDY

..............

316

P
ROBLEM
S
PECIFICATION

................................
..........

317

B
ASIC
A
PPROACH
&

D
ATA
S
TRUCTURE

....................

318

M
AP
C
REATION


A
LGORITHM

................................
..

320

M
AP
C
REATION


E
XAMPLE

................................
......

321

C
REATED
M
AP

................................
..........................

322

M
AP
C
REATION


C
ODE

................................
............

323

M
AP
S
MOOTHING
/W
EATHERING


A
LGORITHM

........

325

M
AP
S
MOOTHING


E
XAMPLE

................................
...

326

S
MOOTHED
M
AP

................................
.......................

327

M
AP
S
MOOTHING


C
ODE

................................
.........

328

C
RATER
A
DDITION


A
LGORITHM

.............................

333

C
RATER
A
DDITION


E
XAMPLE

................................
.

334

C
RATERED

M
AP

................................
........................

335

C
RATER
A
DDITION


C
ODE

................................
.......

336

R
IVER
A
DDITION


A
LGORITHM

................................

340

R
IVER
A
DDITION


E
XAMPLE

................................
....

342

M
AP WITH
R
IVER

................................
......................

343

R
IVER
A
DDITION


C
ODE

................................
..........

344

R
EVIEW

................................
................................
.....

352


MATLAB: Prog. & Prob. Solving

p.
10

2001 Notes

Introduction to MATLAB

• MATLAB is a powerful engineering environment
and language

-

powerful tool in engineering problem solving,
data analysis, modeling and visualisation

-

useful throughout your degre
e & used in other
courses

• Matlab is the vehicle used by this course to teach:

-

problem solving by computer

-

programming

• Today’s lecture is introductory:

-

“driving” Matlab

-

illustration by example


Reference:






For Engineers (Ch. 1 & 2)





Mastering (Ch
. 2, 3 & 34)





User’s (Ch. 1, 23 & “A Quick
Overview”)

MATLAB: Prog. & Prob. Solving

p.
11

2001 Notes

What is Matlab?

MATLAB:


MAT
rix
LAB
oratory


“High performance language for technical
computing”

• Interactive environment incorporating:

-

programming language

-

mathematical calculations (computation)

-

data visualisation

-

large number of inbuilt routines
corresponding to many mathematical,
engineering & science problems

• Typical uses include:

-

mathematical calculations

-

engineering & scientific problem solving

-

modeling & simulation

-

data analysis & visuali
sation

• Basic data structure (unit of computation) of an
array/matrix

-

vector operations

-

natural expression of many engineering &
scientific problems

MATLAB: Prog. & Prob. Solving

p.
12

2001 Notes

History of Matlab

• First introduced at Stanford Uni in 1979

-

initially an interactive shell from which to
call
FORTRAN routines

• Later MathWorks was formed to market Matlab.

• An evolved language

-

initially a collection of things felt to be
necessary

-

little top
-
down design

-

“Like every other scripting language, Matlab began
as a simple way to do powerful things
, and it has
become a not
-
so
-
simple way to do very powerful
things.”
, Webb & Wilson, Dr. Dobb’s Journal,
Jan 1999

• Heavily used by universities world wide in their
engineering and science faculties for teaching

-

(see links off course homepage)

• Used by
scientists and engineers in research,
development and design

MATLAB: Prog. & Prob. Solving

p.
13

2001 Notes

An Initial Example

Population Growth


A colony of micro
-
organisms grows at such a rate
its population doubles every 14.3 hours.


Given an initial population of 1000 organisms,
calculate the popul
ation on an hourly basis for
the period of two days.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% amoeba.m

%


Matlab example to show problem solving. A

%


species doubles its population every 14.3

%


hours. Given an initial population of 1000

%


det
ermine its population hourly

%


for the first two days

% Author: Spike

% Date: 10/2/1999

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%

% Initial “setup” work %

%%%%%%%%%%%%%%%%%%%%%%%%

initialNum = 1000;


% Initial population

d
oublePeriod = 14.3;


% Time in hours to


% double population

interval = 0:48;


% Two days on an hourly







% basis

%%%%%%%%%%%%%%%%%%%%%%%

% Perform calculation %

%%%%%%%%%%%%%%%%%%%%%%%

population =
initialNum*2.0.^(interval/doubleP
eriod);

%%%%%%%%%%%%%%%%%

% Output values %

%%%%%%%%%%%%%%%%%

combined = [interval ; population];

disp('Micro Organism Population');

disp('Hour

Population');

MATLAB: Prog. & Prob. Solving

p.
14

2001 Notes

fprintf('%d
\
t%6.0f
\
n',combined);

MATLAB: Prog. & Prob. Solving

p.
15

2001 Notes

1
st

Example (Cont)

%%%%%%%%%%%%%%%%

% Plot results %

%%%%%%%%%%%
%%%%%

plot(interval,population,'
-
+');

xlabel('Hours'); ylabel(‘Population’);


>> amoeba

Micro Organism Population

Hour

Population

0


1000

1


1050

2


1102


14


1971

15

2069


47


9759

48


10244

Title: amoeba.eps
Creator: MATLAB, The Mathworks, Inc.
Preview: This EPS picture was not saved with a preview (TIFF or PICT)
included in it
Comment: This EPS picture will print to a postscript printer but not to other
types of printers

MATLAB: Prog. & Prob. Solving

p.
16

2001 Notes

Some Features

• Powerful computation engine

• 3
rd

generation

scripting (programming) language

-

functions & argument passing

-

iteration & slection

• Implicitly vectorised operation

• Powerful 2D and 3D plotting capabilities

• Diverse and powerful inbuilt functions

-

linear algebra

-

polynomials

-

fourier analysis

-

integratio
n & differentiation

-

differential equations

• Add
-
on toolboxes for specific problem domains

• multi
-
media capabilities

-

GUI builder

-

Movies & sound

MATLAB: Prog. & Prob. Solving

p.
17

2001 Notes

Running Matlab

Startup Under Unix

Type matlab at the shell prompt:



$
matlab

Or through the workspace menu on
octarine

Startup Under Windows 95/98

From
program

menu select
Student Edition of
Matlab

To Exit

Type
quit

(or
exit
) in the command window:



>>
quit

Or through Matlab’s
File

menu.


MATLAB: Prog. & Prob. Solving

p.
18

2001 Notes

Help & Demos

• Matlab has a extremely comprehensive help

Through the Comm
and Window

help

(e.g.,
help mean
). Most general form of
help. Without options lists all help topics. If
option then provides help for that particular
command. Always start with this.

lookfor

(e.g.,
lookfor 3d
) Look for commands that
are relevant to the top
ic specified.

Through the Help Window

• Window based version of the above

• Invoked from the
help

menu or by typing
helpwin

in the command window.

Through the Help Desk

• Web browser based help, invoked from menu or
by entering
helpdesk

or
doc

in the comma
nd
window.

Demonstrations

MATLAB: Prog. & Prob. Solving

p.
19

2001 Notes

• Large series of examples:
demo

command

MATLAB: Prog. & Prob. Solving

p.
20

2001 Notes

Controlling the Environment

• A list of “meta” commands useful for controlling
the Matlab environment and execution

<cntrl
-
c>


Terminate currently executing
command. Useful if stuck in an
infinite loop.

clc



Clear the screen and home the
cursor.

home


Return the cursor to the top left
corner

more


Force output to be paginated
(presented a page at a time)

diary <fname>

Save all Matlab output in the file
fname

until a
diary off

command is ex
ecuted.
Useful for recording testing results and saving
program output.

echo


Echo to the screen each line as it is
executed until an
echo off

command is received.
Useful for tracing and debugging but generally
confusing for normal program execution.

MATLAB: Prog. & Prob. Solving

p.
21

2001 Notes

A 2
nd

Example

Consider the problem of generating artificial 3D
terrain. Such terrian might be used in virtual
reality simulations (e.g., wargames), to model the
interaction of terrain and species spread etc.


Matlab has powerful 3D graphing tools including
tool
s for generating 3D surface plots.


The terrain can be represented as a 2D grid (x and
y co
-
ordinates) with the height at that point
being saved. Hence a 2D matrix is our basic
numeric representation of the terrain.


How do we generate “realistic” terrain?

Very
difficult due to the many agents responsible
(e.g., erosion, tectonic forces, temperature
extremes) for shaping the terrain. We will accept
an extremely simple model that:

• starts from an initial random configuration
of peaks and valleys and

• appl
ies a simple model of erosion that
smoothes adjacent contour features together.

• simple models for meteor impacts and the
creation of plateaus.

Final Approach

• A set of user functions that perform the following
tasks

-

create an initial random map configur
ation

-

smooth/erode/melt an existing map

-

add a meteor impact to an existing map

MATLAB: Prog. & Prob. Solving

p.
22

2001 Notes

-

add a plateau to an existing map

MATLAB: Prog. & Prob. Solving

p.
23

2001 Notes

Map Generation


>> help mapGen


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


MAPGEN Generate a random map (grid of
elevation data)


[X
,Y,Z] = mapGen()
-

Generate a 50x50 grid
of elevation data


[X,Y,Z] = mapGen(N)
-

Generate an NxN grid
of elevation data


[X,Y,Z] = mapGen(N,M)
-

Generate an NxM grid
of elevation data


>> [X Y Z0] = mapGen(60);

>> surfl(X,Y,Z0);

>> shading interp

>
> colormap copper

>> axis off

>> print
-
deps map0.ps

Title: map0.ps
Creator: MATLAB, The Mathworks, Inc.
Preview: This EPS picture was not saved with a preview (TIFF or
PICT) included in it
Comment: This EPS picture will print to a postscript printer but not
to other types of printers

MATLAB: Prog. & Prob. Solving

p.
24

2001 Notes

Map Smoothing


>> Z40 = mapSmooth(Z0,40);


>> surfl(X,Y,Z40); shading interp; axis off

Title: map40.ps
Creator: MATLAB, The Mathworks, Inc.
Preview: This EPS picture was not saved with a preview (TIFF or
PICT) included in it
Comment: This EPS picture will print to a postscript printer but not
to other types of printers

>> Z41 = mapPlateau(Z40);

>> Z51 = mapSmooth(Z41,10,0.2);

>> surfl(X,Y,Z51); axis off; shading interp;

Title: map51.ps
Creator: MATLAB, The Mathworks, Inc.
Preview: This EPS picture was not saved with a preview (TIFF or
PICT) included in it
Comment: This EPS picture will print to a postscript printer but not
to other types of printers

MATLAB: Prog. & Prob. Solving

p.
25

2001 Notes

M
ap Code

• A quick look at some of the code:

mapGen

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MAPGEN Generate a random map (grid of
elevation data)

% [X,Y,Z] = mapGen()
-

Generate a 50x50 grid
of elevation data

% [X,Y,Z] = mapGen(N)
-

Generat
e an NxN grid
of elevation data

% [X,Y,Z] = mapGen(N,M)
-

Generate an NxM grid
of elevation data

%

% Author: Spike

% Date: 11/10/98

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [X, Y, Z] = mapGen(xSize,ySize)


% Provide a default size if no
ne given

if nargin==0


xSize=50;


ySize=50;

% Else if a square map then set both dimensions

elseif nargin==1


ySize=xSize;

end;


% Create x and y arrays (vectors)

x=linspace(0,1,xSize);

y=linspace(0,1,ySize);

[X Y]=meshgrid(x,y); % Make a grid of a
ll x & y


% The "real" work. Create a set of heights for t

% the map as a matrix of size xSize by ySize.

% Heights are derived from a uniform

% distribution with mean 0 and

% std. dev. of 1.

Z=randn(xSize,ySize);

MATLAB: Prog. & Prob. Solving

p.
26

2001 Notes

Map Code (Cont)

MapPlateau

% Comments re
moved


function newMap =
mapPlateau(oMap,radius,height,xCentre,yCentre)

% Build the map to hold the new heights

newMap=zeros(size(oMap,1),size(oMap,2));


% We don't have an acceptable radius.

% 10% of the length of the shortest side of the

% map.

if (na
rgin==1 |
radius>min(size(oMap,1),size(oMap,2)));


radius=min(size(oMap,1),size(oMap,2))*
(10.0+randn)/100.0;

end;


% We don't have a supplied height. Generate one

% that is roughly the same as the current

% highest peak.

if (nargin<3)


height=max(ma
x(oMap));


height=height*(100.0+2*randn)/100.0;

end;


% No centres provided, or not valid centre.

% Generate a random centre for the plateau.

if
(nargin<5|xCentre<1|xCentre>size(oMap,2)|yCentre
<1|yCentre>size(oMap,1))


xCentre=round(rand*size(oMap,2))
;


yCentre=round(rand*size(oMap,1));

end;


% xVals=1:size(oMap,2);

% yVals=1:size(oMap,1);

MATLAB: Prog. & Prob. Solving

p.
27

2001 Notes

Map Code (Cont)


% For each point on the surface determine

% whether it is now part of the plateau or not.

% If it is then set its height to be height. If

% it

isn't then preserve the old height.

% NOTE: There should be a "cleaner" way of doing

% this without loops (such as the find()

% function) but the calculate of inside or

% outside the circle [needs to be done for i & j

% values simultaneously] seems to

preclude such

% an approach.

for iIndex=1:size(oMap,2)


for jIndex=1:size(oMap,1)


if ((iIndex
-
xCentre)^2+(jIndex
-
yCentre)^2<=radius^2)


newMap(jIndex,iIndex)=height*
(100.0+randn)/100.0;


else


newMap(jIndex,iIndex)=oMap(jInde
x,iIndex);


end;


end;

end;





MATLAB: Prog. & Prob. Solving

p.
28

2001 Notes

Principles of “Good” Programs

• meet specification

-

verifiable

-

dependable

• natural

-

abstraction

-

modularisation

-

encapsulation

¨• understandable

-

maintainable

-

portable

• efficient

• “elegant”

MATLAB: Prog. & Prob. Solving

p.
29

2001 Notes

Review

• Matlab background

-

history

• Chief features of Matlab

• Driving Matlab

-

running Matlab

-

help & demos

-

controlling the command environment

• Examples of Matlab use

• Principles of good programming

MATLAB: Prog. & Prob. Solving

p.
30

2001 Notes

Matlab Syntax

• All programming languages have their own syntax

-

rules for usi
ng the language

• Expressions are the statements that compose a
program

-

effectively the “lines” of a program

• Today’s lecture examines:

-

The rules of Matlab syntax

-

Assignment

-

Commenting

-

Useful Matlab functions

-

Script M
-
Files



References:





F
or Engineers (Ch. 1)




User’s Guide (Ch.1, 2, 4, 24)




Mastering (Ch. 2, 4, Appendix A)

MATLAB: Prog. & Prob. Solving

p.
31

2001 Notes

Some Simple Calculations

• Matlab capable of simple mathematical operations
analogous to a calculator:


>> 9.3 + 5.6


ans =



14.9000


>> 13.1
-

4.113


ans =



8
.9870


>> 10.1 * 890.99


ans =



8.9990e+03


>> 9.6 / 3.2


ans =



3.0000


>> 9.9 ^ 3.1


ans =



1.2203e+03


>> diary off

MATLAB: Prog. & Prob. Solving

p.
32

2001 Notes

Basic Mathematical Operators

• The following basic mathematical operators are
supported by Matlab:


Operation

Symbol

Addition
(a + b)

+

Subtraction (a
-
b)

-

Multiplication (a . b)

*

Division (a


b)

/ or
\

Exponentiation (a
b
)

^


MATLAB: Prog. & Prob. Solving

p.
33

2001 Notes

Expressions

• Single lines (calculations or commands) of Matlab
have one of two general forms:



variable = expression


y=sin(3.14);

z=(y*4.6)^12.9


13.456;

or



expression


plot(x,y,’
-
+’);

z^3.5


• Where the expressions are a combination of:

-

mathematical & other built
-
in operators

-

variables

-

built
-
in function names

-

user defined functions

-

bracketing for precedence

MATLAB: Prog. & Prob. Solving

p.
34

2001 Notes

Variables & Assignment

• Of
ten we wish to perform a calculation and save a
copy of the result

• general form:



<variable> = <calculation>


e.g., resultInPercent = labOutOf50 + examOutOf50;

=


The assignment operator

-

read as:
"becomes equal to”

-

transfers the results of the calc
ulation on the
right
-
hand side to the variable on the left
-
hand side.

• For instance



resultInPercent = labOutOf50 + examOutOf50;

-

the variable
resultInPercent

becomes equal to the
sum of the values stored in
labOutOf50

and
examOutOf50


labOutOf50
examOutOf50
resultInPercent
29.4
38.5
67.9
+
=

MATLAB: Prog. & Prob. Solving

p.
35

2001 Notes

The
ans

variabl
e

• The results of calculations do not need to be saved
to a variable explicitly.

• If no variable is specified then the result is
automatically saved to the
ans

(answer) variable.

-

This variable may be subsequently used


e.g.,

>> 91.3


14

ans =



77.
3


>> z=ans * 2

z =



144.6

• In general you should not use ans but your own
meaningfully named variables

Examining a Variable’sValue

• Simply typing a variable’s name alone is
interpreted as a command to show the value
stored in that variable


e.g.,

>>z


z =


MATLAB: Prog. & Prob. Solving

p.
36

2001 Notes


144.6

MATLAB: Prog. & Prob. Solving

p.
37

2001 Notes

Semicolon, Comma & Period

• By default Matlab interprets the end of a line as the
end of a statement/expression

Semicolon

• Semicolon
;

terminates the current expression
and

suppresses output (to the screen) of the result


e.g., volume =

pi * radius^2 * height;

The value is calculated and stored in volume but
not echoed back to the screen.

• A semicolon should be used on most lines of code
as we are not interested in intermediary results

Comma

• The comma
,

can be used to separate multipl
e
statements on the same line. The value of any
variables will be echoed to the screen.


e.g., x=5.7, y=89.12

will echo those variables and their names back
on the screen.

Period

• Long statements can be split over lines by 3
periods


MATLAB: Prog. & Prob. Solving

p.
38

2001 Notes

e.g., incomeInHand =
salary


tax


unionFee …




-

superAnnuation;

MATLAB: Prog. & Prob. Solving

p.
39

2001 Notes

Layout Conventions

• Very little restriction on layout in Matlab programs

• However common layout conventions make
programs easier to…

-

read

-

understand

-

maintain

• Basic conventions:

-

one statement (on th
ought) per line

-

indent lines to show different parts of program

-

blank lines separate different parts of program

-

comments help readers (including the author!)
understand the program

-

break long lines into readable segments

MATLAB: Prog. & Prob. Solving

p.
4
0

2001 Notes

Comments

• Matlab’s comment

character is the percent
-
symbol
%

-

remainder of the line past the % is ignored by
the computer

• Comments are for the humans:

-

help us understand what is occurring in the
program

• Good comments:

-

provide information not immediately obvious

-

described

the intended effect of the portion of
code to which they refer

-

conform to usual conventions of prose

-

are always correct and up to date

-

are clearly distinguishable from the
surrounding code (well set apart)

MATLAB: Prog. & Prob. Solving

p.
41

2001 Notes

Using Comments

• A minimum set of comments in a
ny program
should include:

-

the name of the program

-

the program's purpose (what it does)

-

who wrote the program and when

-

any underlying assumptions made during
coding

-

description of any (non
-
obvious) variables

-

description of the purpose of each m
ajor
subsection of the program:

• important formula

• functions

• major loops and control structures

MATLAB: Prog. & Prob. Solving

p.
42

2001 Notes

Comments & Matlab Help

• Matlab adopts a convention in which comments
serve to document individual programs and
functions:

-

when
help

is invoked on a scri
pt file or function
all comment lines up to the first line of code
or a blank line are shown as help for that
function/script.

The Script File helpex.m

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% helpex.m

%

An example of the way Matlab

%

uses comments and h
elp to

%

document a script. If you type

%

help helpex you will see all of

%

these comments up till the first

%

blank line below.

% Author: Spike

% Date: 11/2/1999

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


% This comment won't be seen


x=9.1;

% Do somethin
g trivial


Running Matlab

>> help helpex

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


helpex.m



An example of the way Matlab



uses comments and help to



document a script. If you type



help helpex you will see all of



these comments up till the first



b
lank line below.


Author: Spike

MATLAB: Prog. & Prob. Solving

p.
43

2001 Notes


Date: 11/2/1999


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

MATLAB: Prog. & Prob. Solving

p.
44

2001 Notes

Some useful Mathematical Functions

• Matlab contains literally hundreds of built
-
in
functions

Name

Function

abs(x)

Absolute value

acos(x)

Inverse cosine

acosh(x
)

Inverse hyperbolic cosine

angle(x)

Phrase angle

asin(x)

Inverse sine

asinh(x)

Inverse hyperbolic sine

atan(x)

Inverse tangent

atanh(x)

Inverse Hyperbolic tangent

ceil(x)

Round towards +infinity

conj(x)

Complex conjugate

cos(x)

Cosine

cosh(x)

Hy
perbolic cosine

exp(x)

Exponentiation e^x

fix(x)

Round towards zero

floor(x)

Round towards

infinity

gcd(x,y)

Greatest common divisor

imag(x)

Complex imaginary part

lcm(x,y)

Least common multiple

log(x)

Natural logarithm

log10(x)

Common (base 10) l
ogarithm

real(x)

Complex real part

rem(x,y)

Remainder after division

round(x)

Round towards nearest int

sign(x)

Sign

sin(x)

Sine

sinh(x)

Hyperbolic sine

sqrt(x)

Square root

tan(x)

Tangent

tanh(x)

Hyperbolic tangent



From Version 5.0 User’s Guid
e, Prentice Hall,
1998.


e.g.,


distance = sqrt((x1
-
x2)^2+(y1
-
y2)^2);


height = velocity*sin(launchAngle)*time
-



MATLAB: Prog. & Prob. Solving

p.
45

2001 Notes




0.5*gravity*time*time;

MATLAB: Prog. & Prob. Solving

p.
46

2001 Notes

Script M
-
Files

• Re
-
entering the same program (set of instructions)
multiple times is wasteful

-

ideally need a means

of creating
once

and
re
-
using

as required

Script (M
-
Files)

are Matlab's mechanism for this

• We will use these

extensively

Basic Approach using M
-
Files


1.

Create m
-
file with a text editor (or
Matlab's built
-
in Script editor).

2.

In Matlab command window enter
name
of script file (e.g., if file called
example1.m

then enter
example1
) to
run it.

3.

While still errors in the script

3.1

Modify & save script using
editor

3.2


Rerun script in Matlab

Naming

• M
-
files (scripts) must all have the suffix
".m"

-

When a script name is

entered Matlab
"tacks" a ".m" on the end and looks for a file
of that name

MATLAB: Prog. & Prob. Solving

p.
47

2001 Notes

e.g., >> amoeba


Matlab searches for a file called amoeba.m

MATLAB: Prog. & Prob. Solving

p.
48

2001 Notes

Matlab Name Space

• Matlab employs the following rules in resolving an
identifier entered by the user (e.g., aristotl
e):


1.

Looks for a variable (aristotle) in the
current workspace…if that is not found…

2.

Looks for a built
-
in function
(aristotle())…if that is not found…

3.

Looks for a script/m
-
file (aristotle.m)
in the Matlab's current directory
(generally the one it was start
ed in)…if
that is not found…

4.

Looks for a script/m
-
file (aristotle.m)
in Matlab's search path (in the order
listed in the search path)

Matlab Search Path

• If an M
-
file can not be found by Matlab there are
two possible solutions:

-

In Matlab command window
cd

to
directory containing M
-
file

-

Add the directory containing the M
-
file to
Matlab's search path:


addpath

command


path browser

(GUI interface)

MATLAB: Prog. & Prob. Solving

p.
49

2001 Notes

• useful approach when several related M
-
files

MATLAB: Prog. & Prob. Solving

p.
50

2001 Notes

Review

• Matlab as calculator

• Expressions in Matlab

• Variab
les & assignment

-

assignment operator

-

default variable (ans)

• Separators

-

comma; seni
-
colon; 3
-
periods

• Layout conventions & comments

• Script M
-
files

MATLAB: Prog. & Prob. Solving

p.
51

2001 Notes

MATLAB Variables & Data Types

• Variables & their usage form a vital part of
problem solving in any

language:

-

"containers" for user supplied values

-

intermediary working values

-

final results

• Each programming language has its own syntax
(rules) regarding variables:

-

declaration

-

valid identifiers

• Different languages support different basic data
types an
d have their own rules regarding the
different types

-

integer, reals, strings etc.

• Today's lecture explores these two areas as applied
to Matlab

References:

For Engineers (Ch. 1)





User's Guide (Ch. 1, 3, 9)





Mastering (Ch.. 2, 5, 10)

MATLAB: Prog. & Prob. Solving

p.
52

2001 Notes

Variables

• Pro
grams model some aspect of the real world

data objects (variables) which the program employs
& manipulates thus represent some object or
concept in the real world


• In Matlab a variable has

-

name

• an identifier (or handle)

• selected to indicate what real

world object it
represents

-

data type

• what values can the variable have?

• what operations can be performed upon it?

• all Matlab variables have a default type
(class) which is a vector of real numbers

MATLAB: Prog. & Prob. Solving

p.
53

2001 Notes

Identifiers

• Names created by the programmer to rep
resent
various objects (quantities) in the program

• Syntax:

-

No white
-
space (e.g., class total is not valid)

-

Must start with a letter (e.g.,
k9

is valid,
2tango

is not)

-

Can be composed from letters, digits, &
underscores (e.g.,
class_total

is valid,
class
-
total

is not valid)

-

Can have up to 31 characters (those beyond 31
are ignored)

-

Is case sensitive (e.g.,
highscore

and
highScore

are
two different variables)

• Avoid pre
-
defined function and reserved words
(e.g., "for", "mean" etc. as these replace the buil
t
-
in functions)

MATLAB: Prog. & Prob. Solving

p.
54

2001 Notes

Meaningful Identifiers

• Identifiers should communicate their
purpose

(meaning


what they represent)
clearly

and
precisely

without undue verbosity

Some Examples



s1


vs. student1



the_first_student_on_the_course vs.
first_student



N, k
, m, n



(OK for maths)



student1 & student2

(try to avoid similar names)



high_score

or highScore



(two conventions for composite ids)

MATLAB: Prog. & Prob. Solving

p.
55

2001 Notes

Weak Typing

• Unlike many 3
rd

generation languages, Matlab is
extremely weakly typed:

-

no declaration of variables b
efore use

-

one major type of data (variable) with a few
special cases & additions

• by default everything is a vector (1
-
dimensional array) of real numbers

• single values (scalars) simply a vector with
a single element


e.g.



single = 9.3;

% A vector
with one


% element







% i.e., a scalar




countDown = 10:
-
1:1;

% A vector:


% 10, 9,…,1




average = mean(values);


% May be a scalar,






% vector or matrix

MATLAB: Prog. & Prob. Solving

p.
56

2001 Notes

Impl
ications of Weak Typing

• This approach has several advantages & dis
-
advantages:

-

very powerful things may be expressed (&
hence solved) very easily, but there is little
"protection"

Advantages

• Shorter initial learning curve: can write useful
programs nea
rly immediately

• Implicit vectorisation (everything treated a a
vector) leads to simpler and more intuitive
programs

Disadvantages

• No protection for users from simple errors (e.g.,
typed
results=x+y

instead of
result=x+y;
)

• Single statements become har
der to understand
(e.g., does
average=mean(values);

produce a scalar,
vector or array?)

• More difficult to closely match real
-
world objects


MATLAB: Prog. & Prob. Solving

p.
57

2001 Notes

Special (Built
-
in) Constants &
Variables

• Matlab has a number of built
-
in constants and
variables



Name

Descript
ion

ans

Default destination for
results

pi

Ratio of circle circumference
to diameter

eps

Smallest number such that
x+eps ‡ x

flops

Floating point operations
performed

int

Infinity

Nan or
nan

Not
-
a
-
number (undefined)

I & j


-
1 (square root of

1)

nargin

Number of arguments supplied
to a function

nargout

Number of arguments output by
a function

realmin

The smallest usable positive
real number

realmax

The largest usable positive
real number

† After Version 5.0 User's Gui
de, Prentice Hall,
1998

MATLAB: Prog. & Prob. Solving

p.
58

2001 Notes

Complex Numbers

• Matlab implicitly supports complex numbers

-

no requirement for special functions to
manipulate

• For example


EDU» z1=sqrt(
-
4)+3

z1 =


3.0000+ 2.0000i


EDU» z2=z1*(1
-
i)

z2 =


5.0000
-

1.0000i


EDU» z3=5.6*sin(1
.55)*i

z3 =


0+ 5.5988i


EDU» r1=imag(z3)


r1 =


5.5988


EDU» z4=mean([z1 z2 z3])

z4 =


2.6667+ 2.1996i

• Note:

-

mathematical and built
-
in function usage is
exactly the same as for non
-
complex

-

complex expressions yield complex values

MATLAB: Prog. & Prob. Solving

p.
59

2001 Notes

Nan & inf



Mathematical operations can often yield undefined
results or those beyond the storage capability of
the machine

• In many languages these type of operation (e.g.,
division by zero) cause the running program to
crash

-

not particularly desirable

• Matlab h
as two special "constants" which are
substituted when such operations occur:

Nan

Not A Number

inf


Infinity

-

this allows recovery or continuation

• For example:


EDU» undef=0/0

Warning: Divide by zero.

undef =


NaN


EDU» big=1/0

Warning: Divide by zero.

b
ig =


Inf


EDU» big2=2^realmax

big2 =

MATLAB: Prog. & Prob. Solving

p.
60

2001 Notes


Inf

MATLAB: Prog. & Prob. Solving

p.
61

2001 Notes

Strings

• Not all real
-
world objects are best represented by
numbers

-

e.g., names, addresses, units of measurement

• A common type supported by most languages
(including Matlab) is the String

-

a collection o
f characters

• Indicated by the single
-
quote '


EDU» str1='My first string'

str1 =

My first string


EDU» findstr(str1,'first')

ans =


4


EDU» strcmp(str1,'My')

ans =


0

EDU» strncmp(str1,'My',2)

ans =


1


EDU» str2='45.6'

str2 =

45.6


EDU» str2
num(str2)

ans =


45.6000


EDU» strcat(str1,str2)

MATLAB: Prog. & Prob. Solving

p.
62

2001 Notes

ans =

My first string45.6

MATLAB: Prog. & Prob. Solving

p.
63

2001 Notes

Managing Variables

• The variables created during a Matlab session are
not persistent objects:

-

they cease to exist when the session is over

-

endure for the duration of the sess
ion

• Matlab provides the following commands for
managing the workspace

clear

• delete a variable now


EDU» x=7.9

x =


7.9000


EDU» clear x

EDU» x

??? Undefined function or variable 'x'.

• Useful if you wish to ensure that a variable starts
with no valu
e

-

initialisation

MATLAB: Prog. & Prob. Solving

p.
64

2001 Notes

Managing Workspace: load

• Load in a variable that has previously been saved
from Matlab or another source


EDU» linear=1:10

linear =


1 2 3 4 5 6 7 8
9 10


EDU» save linear

EDU» clear linear

EDU» l
inear

??? Undefined function or variable 'linear'.


EDU» load linear

EDU» linear

linear =


1 2 3 4 5 6 7 8
9 10

• Useful for large and/or important data

MATLAB: Prog. & Prob. Solving

p.
65

2001 Notes

Managing Workspace: save

• Save a matlab variable to a file for
usage in a later
session


EDU» squares=linear.^2

squares =


1 4 9 16 25 36 49 64
81 100


EDU» save mydata linear squares

EDU» clear linear squares

EDU» squares

??? Undefined function or variable 'squares'.

EDU» load mydata

EDU» sq
uares

squares =


1 4 9 16 25 36 49 64
81 100

MATLAB: Prog. & Prob. Solving

p.
66

2001 Notes

Review

• Variables & identifiers

• Data types in Matlab

-

implications

• Special Constants & Variables

-

inf & nan

• Complex numbers

• Strings

• Managing variables

MATLAB: Prog. & Prob. Solving

p.
67

2001 Notes

I/O in MATLAB

• All p
rogramming languages possess instructions
for obtaining input (generally from the user) and
outputting results

-

without input a program always computes the
same result

-

without output a program is effectively useless

• Matlab has an unusual mixture of I/
o instructions

-

a simple input and output statement useful in
most cases

-

a set of more complex functions heavily based
on C’s
fprintf

&
fscanf

• Today’s lecture looks at:

-

the syntax of these statements

-

how they can be used to increase the
functional
ity of programs


References:

For Engineers (Ch. 1, 8)





User’s Guide (Ch. 3, 4)





Mastering (Ch. 3, 4, 5)

MATLAB: Prog. & Prob. Solving

p.
68

2001 Notes

Basic Input

• Matlab has a simple, single statement known as
input

that serves to both:


-

prompt for an input and

-

return what the user read.

T
he Input Statement

• General syntax


<variable> = input(prompt
-
string);


e.g.,

height=input(‘Enter the initial drop height ‘);


meanWeight=80.0;

% Mean weight of a single






% aicrew member in kgs

crewWeight = meanWeight * …


floor(input(‘How many ai
r
-
crew today? ‘));

• Function:

-

print the prompt
-
string on the screen (without a
return character)

-

wait for the user to enter a value at the
keyboard

-

place that value in the variable on the left
-
hand
-
side of the expression

MATLAB: Prog. & Prob. Solving

p.
69

2001 Notes

Inputting Strings

• By default the

input statement reads only numeric
values

-

see below regarding expressions

-

must explicitly state we are reading a string


<variable>=input(prompt,string
-
read);


e.g.,

name=input(‘Please enter your name’,’s’);

MATLAB: Prog. & Prob. Solving

p.
70

2001 Notes

Behaviour of Input Statement

• Consider the fol
lowing example:


>> ex1=input('1st number...')

1st number...10


ex1 =

10


>> ex2=input('2nd input...')

2nd input...34 45

?
??? 34 45


|

Unrecognized operand or partial expression.

2nd input...34


ex2 =

34


>> ex3=input('3rd input...')

3rd input...ex2*
100
-
ex1 + 7.6


ex3 =

3.3976e+03

• Will re
-
prompt until acceptable input received

• Will accept expressions in the Matlab language!

-

shouldn’t seek to exploit this fact (but how to
stop users?)

MATLAB: Prog. & Prob. Solving

p.
71

2001 Notes

Micro: Amoeba Expansion

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%

% micro.m

% A colony of micro organisms grows at such a

% rate that its population doubles after a

% specified number of hours.The user supplies an

% initial population size, name for the species,

% and interval required to double in size a
nd

% the script charts the progress for the first

% 48
-
hours.

% A modification of the amoeba script to

% illustrate the utility of the input statement.

% Author: Spike

% Date: 15/2/1999

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


species = input(
'What is the organism''s name?
','s');


initialNum = input('Please enter the initial
number of species...');


doublePeriod = input('Please enter the number of
hours required for the population to
double...');


interval = 0:48;


% Two days


population =
ini
tialNum*2.0.^(interval/doublePeriod);


combined = [interval ; population];

disp(strcat(species,' Organism Population'));

disp('Hour

Population');

fprintf('%d
\
t%6.0f
\
n',combined);


plot(interval,population,'
-
+');

xlabel('Hours');

ylabel('Population');

MATLAB: Prog. & Prob. Solving

p.
72

2001 Notes

Micro

Run

>> micro


What is the organism's name? little
-
us nastius


Please enter the initial number of species...1e5


Please enter the number of hours required for
the population to double...5.34


little
-
us nastius Organism Population


Hour

Population

0

100000

1 113860


18

1034446

19

1177824

20

1341075


45

34416732

46

39187024

47

44618498

48

50802794



MATLAB: Prog. & Prob. Solving

p.
73

2001 Notes

Basic Output

• Matlab has a simple single statement called
disp

for displaying values

-

displays literals and values of variables

-

format controlled by a separate c
ommand

The disp Statement

• General forms:


disp(variable);


OR


disp(expression);


e.g.,

>> disp(ex1);


10


>> disp('Text such as for table headings');

Text such as for table headings

>> disp('The value of ex2=',ex2);

?
??? Error using ==> disp

Too many

input arguments.


>> disp(strcat('10 times ex2 equals
',num2str(10*ex2)));

10 times ex2 equals340

• Displays only a single argument

• Argument can be an expression

MATLAB: Prog. & Prob. Solving

p.
74

2001 Notes

The format command

• Matlab has a default behavior when outputting
numeric values:

-

if value

is a whole number then display as an