Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  ·...

146
01_INTRODUCTION Trust The Computer. The Computer is Your Friend. Computer Credo, from the computer game Paranoia Computer Programming for Engineers ENCMP 100 2 Introduction ©2011 by ECE, UofA Computers – are everywhere ENCMP 100 3 Introduction ©2011 by ECE, UofA Computers – Obvious Places Personal computers, hand calculators, Personal Data Assistants (PDAs), smart phones, game systems used by us to perform variety of tasks related to work and entertainment Mainframe computers: used by large organizations to host the centralized databases and enterprise software Transaction computers: used by on-line banks, stock markets, air reservation systems, lottery networks, etc. Embedded computers: used – almost everywhere – to control systems without necessarily interacting directly with humans through a conventional keyboard and/or display ENCMP 100 4 Introduction ©2011 by ECE, UofA Computers – not-so Obvious Places Appliances (TV & DVD, microwave, washer & dryer …) Communications equipment, cell phones Navigation systems (e.g., Global Positioning System) Cars, trucks, trains, aircrafts, submersibles, spacecrafts Medical equipment, measurement & monitoring devices Factories, production lines, machinery Just about every modern engineering system is controlled by one or more embedded computers and/or computers with conventional user interfaces (BMW 740i sedan has over 100 computers). 1

Transcript of Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  ·...

Page 1: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

01_INTRODUCTION

Trust The Computer. The Computer is Your Friend.

Computer Credo,

from the computer game Paranoia

Computer Programming for Engineers

ENCMP

100

2Introduction ©2011 by ECE, UofA

Computers –

are everywhere

ENCMP

100

3Introduction ©2011 by ECE, UofA

Computers – Obvious Places

• Personal computers, hand calculators, Personal Data Assistants (PDAs), smart phones, game systems used by us to perform variety of tasks related to work and

entertainment

• Mainframe computers: used by large organizations to host the centralized databases and

enterprise software

• Transaction computers: used by on-line banks, stock markets, air reservation systems,

lottery networks, etc.

• Embedded computers: used – almost everywhere – to control systems without necessarily

interacting directly with humans through a conventional keyboardand/or display

ENCMP

100

4Introduction ©2011 by ECE, UofA

Computers – not-so Obvious Places

• Appliances (TV & DVD, microwave, washer & dryer …)

• Communications equipment, cell phones

• Navigation systems (e.g., Global Positioning System)

• Cars, trucks, trains, aircrafts, submersibles, spacecrafts

• Medical equipment, measurement & monitoring devices

• Factories, production lines, machinery

• Just about every modern engineering system is controlled by one or more embedded computers and/or computers with conventional user interfaces (BMW 740i sedan has over 100 computers).

1

Page 2: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

01_INTRODUCTION

ENCMP

100

5Introduction ©2011 by ECE, UofA

Computers – Applications and Benefits

• Faster and larger-scale numerical computation; large-scale information collection, storage, processing, and distribution; accurate modeling and simulation of systems

• Programmable control of machines and systems to achieve increased flexibility and higher efficiency

• High-speed Internet; enhanced education; employment at a distance and telecommuting; digital publishing, multimedia, and entertainment; altered and (hopefully)

enhanced social interaction; enhanced communication and trade among cultures

ENCMP

100

6Introduction ©2011 by ECE, UofA

Computers – Hardware & Software

• Hardware refers to the tangible enclosures, power supplies, cooling system, wiring, electronics, etc. that make up a computer.

• Software refers to the program data that is stored in the memory of a computer. Programs are made up of instructions and (possibly) embedded constant data.

ENCMP

100

7Introduction ©2011 by ECE, UofA

Programming Languages

• It is possible for humans to write a program using the computer's "native" binary machine language in binary (0's and 1's) format. However, this is almost always impractical because humans make too many errors

and are not productive producing long sequences of 0's and 1's.

• Computer programming languages are textual notations that allow programs to be expressed in a much more convenient "human-friendly" format.

ENCMP

100

8Introduction ©2011 by ECE, UofA

Programming Languagescontinuous development

• In 1954 John Backus invented the first high-level programming language, FORTRAN (FORmula TRANslation) at IBM Corp.

• In 1993, he was awarded the U.S. National Academy of Engineering's Charles Stark Draper Prize, the highest prize awarded in engineering, for the invention of FORTRAN.

• Many different programming languages have been developed since ‘50s. They satisfy needs of different users, they are also tuned to variety of applications.

• Some of popular programming languages are: Visual Basic, C/C++, C#, Java, Ruby, Python.

2

Page 3: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

01_INTRODUCTION

ENCMP

100

9Introduction ©2011 by ECE, UofA

Computers – What They Do?

They are useful, omnipresent, are composed of hardware and software – but what they really do?

1. get data

2. process data

3. output processed data

ENCMP

100

10Introduction ©2011 by ECE, UofA

ENCMP 100 – Reason

• Computer and computer-based systems are used to:

• analyze and process data of any type and origin

• design, analyze and simulate variety of systems

• control engineering processes

• Computers and computer-based systems …

should do what YOU what them to do

ENCMP

100

11Introduction ©2011 by ECE, UofA

ENCMP 100 – Goal

• It is important that ALL OF YOU gain an understanding

of the capabilities of computer technology as well as challenges of software design.

• In your engineering careers you will need to design,

modify or at least use computer programs to perform variety of tasks.

• Many of you will have careers specialized in computer-

related or -based technologies, or will use computers in your profession: there is no industry without computers

ENCMP

100

12Introduction ©2011 by ECE, UofA

ENCMP 100 and MATLAB

• In the early 1980s Cleve Moler developed a software system for numerical calculations at the University of New Mexico.

• In 1984 he co-founded MathWorks Inc. to commercialize MATLAB (MATrix LABoratory).

• MATLAB's capabilities have been extended to include a large number of specialized "toolboxes" as well as the SIMULINK product.

• In ENCMP 100 we will be using the MATLAB (MATrixLABoratory) programming language.

3

Page 4: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

01_INTRODUCTION

ENCMP

100

13Introduction ©2011 by ECE, UofA

MATLAB

• MATLAB is a high-level language and interactive environment that enables you to perform computationally intensive tasks faster than with traditional programming languages such as C, C++,

and Fortran. It allows you to quickly validate your ideas and concepts.

• TOOLBOXES are collections of routines implementing algorithms for specific technical tasks, for example, image processing, optimization, statistics,

• SIMULINK is an environment for multi-domain simulation and Model-Based Design for dynamic and embedded systems.

ENCMP

100

14Introduction ©2011 by ECE, UofA

MATLAB

ENCMP

100

15Introduction ©2011 by ECE, UofA

MATLAB – Applications

• Technical Computing

• Control Systems

• Digital Signal Processing

• Communications Systems

• Image and Video Processing

• Test and Measurement

• Computational Biology

• Computational Finance

and more…

ENCMP

100

16Introduction ©2011 by ECE, UofA

MATLAB – Testimonials

We get more data than we can possibly sift through. MATLAB is

our workhorse for viewing, sharing, and processing that data.

Skip Essma, Toyota Racing Development

MATLAB is far and away the best development environment with

just the right combination of power and ease of use for engineering

and scientific applications.

Dave Cogdell, Timken Research

More testimonials:

www.mathworks.com/products/matlab/userstories.html?by=industry

4

Page 5: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

01_INTRODUCTION

ENCMP

100

17Introduction ©2011 by ECE, UofA

MATLAB – Advantages

• Easy to use: simple interpreted language, similar to Basic

• Platform independence: supported on many different compute systems

• Predefined functions: extensive libraries of

functions implementing variety of algorithms

• Device-Independent Plotting: many integral

plotting and imaging commands

• Graphical User Interface: tools for constructing GUI

• MATLAB Compiler: compilation of a MATLAB program into a stand-alone executable

ENCMP

100

18Introduction ©2011 by ECE, UofA

MATLAB – AdvantagesExample: Data Visualization

Demo:

www.mathworks.com/videos/matlab/visualizing-data.html

ENCMP

100

19Introduction ©2011 by ECE, UofA

MATLAB – Disadvantages

• It is an interpreted language and therefore can

execute more slowly then compiled languages – can be mitigated by properly structuring MATLAB programs, and by the use of a compiler

• A full copy of MATLAB is more expensive than a conventional C or Fortran compiler

ENCMP

100

20Introduction ©2011 by ECE, UofA

ENCMP 100 – You will:

• Learn how to apply top-down design methodology to develop software, and in particular

• Learn about different data types

• Learn how to use different flow control constructs

• Learn how to design and develop your own functions

• Gain familiarity with the capabilities of MATLAB, and learn how to use MATLAB’s to construct your own programs starting with data input via data processing to data visualization

5

Page 6: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

Introduction to MATLAB Environment

ENCMP

100

2©2011 by ECE, UofA

MATLAB Environment

When MATLAB executes, it display several windows that accept commands or display information.

Three most important ones are:

Command Windows

where commands are entered

Figure Windows

which display plots and graphs

Edit Windows

which permit a user to create and modify programs

MATLAB Desktop

ENCMP

100

3©2011 by ECE, UofA

MATLAB Desktop

The windows initially "anchored" to MATLAB’s special window called desktop are:

• Command Window

• Command History Window

• Current Folder & Workspace Browser Window

Other MATLAB windows will pop up on top of the MATLAB desktop in response to various commands:

• Edit Window

• Figure Window(s)

• Help Browser Window

• Path Browser Window

MATLAB Desktop

ENCMP

100

4©2011 by ECE, UofA

MATLAB Desktop

MATLAB Desktop

6

Page 7: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

5©2011 by ECE, UofA

MATLAB Command Window

• Commands are typed after the >> prompt, and then followed by

typing the ENTER key.

• The command is then executed

immediately.

MATLAB Desktop

ENCMP

100

6©2011 by ECE, UofA

MATLAB as Calculator

•In its simplest form MATLAB can be used as a scratch

pad – calculator – performing mathematical operations.

•The calculations are performed in the Command

Window, using symbols +, -, *, /, and ^ for addition, subtraction, multiplication, division, and exponentiation, respectively.

•After an expression is typed, the results will be automatically calculated and displayed.

MATLAB Desktop

ENCMP

100

7©2011 by ECE, UofA

MATLAB as Calculator

MATLAB Desktop

ENCMP

100

8©2011 by ECE, UofA

MATLABEllipsis (...) extends commands across lines

MATLAB Desktop

7

Page 8: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

9©2011 by ECE, UofA

Basics of ProgrammingVariables and Constants

MATLAB Desktop

variable

a symbolic name associated with a value and whose

associated value may be changed, a variable can represent any kind of data that can be stored in a computer system, from simple True/False to numbers, names, pictures, sounds

for example: area, radius

constant

a special kind of variable whose value cannot typically be altered by the program during its execution

for example: pi

ENCMP

100

10©2011 by ECE, UofA

Basics of ProgrammingExpressions and Assignments

MATLAB Desktop

expression

is a combination of explicit values, constants, variables,

and functions which computes and then produces another value

for example: 2+3 is an arithmetic expression which evaluates to 5; a relational expression 4==4 evaluates

to true

assignment

a statement where a value on the right side is assigned to a variable on the left

variable = expression

ENCMP

100

11©2011 by ECE, UofA

Basics of ProgrammingArithmetic Functions of Variables

• Addition: a + b

• Subtraction: a - b

• Multiplication: a * b

• Division: a / b

• Exponentiation: a ^ b

These functions can be used to construct expressions

involving constants and/or variables that can be

assigned to variables.>> sum = 8 + 1;

>> product = 2 * 5;

>> result1 = sum / product;

Parentheses can be used in expressions to force the

order of evaluation in expressions.>> result2 = 2^((8+2)/5)

MATLAB Desktop

ENCMP

100

12©2011 by ECE, UofA

MATLAB and Variables

Variable "radius" is created and loaded with its first value.

Variable "pi" is a special variable that is predefined and preloaded with 3.14...

Variable "area" is created and loaded with the simplified value of the right-hand expression.

MATLAB Desktop

8

Page 9: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

13©2011 by ECE, UofA

Semicolon (;) at the End of Line

Typing a semicolon at the end of a command suppresses the output.

The value of a variable can always be seen by typing its name followed by RETURN, without using a ";".

MATLAB Desktop

ENCMP

100

14©2011 by ECE, UofA

MATLAB and Arrays

• The fundamental unit of data in MATLAB is the array.

• An array is a collection of data values organized in rows and columns, and is known by a single name.

• Individual data values are accessed by including the name of the array followed by subscripts in

parenthesis that identify the row and column of the particular value. Even scalars are treated as arrays with one row and one column.

MATLAB Desktop

ENCMP

100

15©2011 by ECE, UofA

Arrays – Examples

Example of a one-dimensional array:>> A = [ 13 57 24 49 70 27 ];

>> A(3)

A(3) =

24

>> A(2:5)

A(2:5) =

57 24 49 70

>> A

A =

13 57 24 49 70 27

and two-dimensional one:>> B = [ 3 5 7; 9 0 2 ]

B =

3 5 7

9 0 2

MATLAB Desktop

ENCMP

100

16©2011 by ECE, UofA

MATLAB and Matrix Operations

2 x 3 matrix A

3 x 3 matrix B

2 x 3 product AxB

MATLAB Desktop

9

Page 10: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

17©2011 by ECE, UofA

M-files in MATLAB

• While MATLAB commands can be typed in by the user (using MATLAB interactively, like a calculator), most typical calculations will need to be stored as sequences of commands.

• Those sequences are stored in files, and the entire file can be executed by typing its name in the Command Window.

• Such files are called "scripts" or "programs”.

• In MATLAB they are also known as “M-files”, because they have the file extension “.m”.

MATLAB Desktop

ENCMP

100

18©2011 by ECE, UofA

M-files in MATLAB

• M-files can be executed manually as separate commands, or they can be called by other M-files.

• M-files provide the main mechanism in MATLAB for managing the complexity of software.

• A library of smaller and simpler component M-files can be developed, and then these M-files can be used as building blocks for creating more complex M-files.

MATLAB Desktop

ENCMP

100

19©2011 by ECE, UofA

Simple M-file Program

• The order of the four lines gives the execution order.

• Three variables are created: radius, area, string

• One predefined variable is used: pi (3.14159265...)

• The "=" symbol causes the expression on the right

side to be evaluated to one result, and then assigned as the new value to the variable on the left side.

• num2str is a built-in format conversion function.

• disp is a built-in output display function.

radius = 2.5;

area = pi * 2.5^2;

string = ['The circle area is ' num2str(area)];

disp(string);

MATLAB Desktop

ENCMP

100

20©2011 by ECE, UofA

Edit Window

MATLAB Desktop

• To create or modify M-files you use the Edit Window.

• The Edit Window is created automatically when you create a new M-file or when you open an existing one.

• The Edit Window is essentially a programming text editor. It also serves as a debugger (later).

• By default, the Edit Window is an independent window not docked to the desktop. It can be docked by you.

10

Page 11: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

21©2011 by ECE, UofA

Creating a New M-file

New filebutton

Edit Window

MATLAB Desktop

ENCMP

100

22©2011 by ECE, UofA

Saving a New (or an Existing) M-file

Save filebutton

Save filedialogue

box

MATLAB Desktop

ENCMP

100

23©2011 by ECE, UofA

Editing an Existing M-file

1. Point to the file name in the current Directory window.

2. Double-click the left mouse

button.3. This will cause an Edit

Window to pop up.

MATLAB Desktop

ENCMP

100

24©2011 by ECE, UofA

Undocked Edit WindowDock

button

MATLAB Desktop

11

Page 12: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

25©2011 by ECE, UofA

Docked Edit WindowUndockbutton

MATLAB Desktop

ENCMP

100

26©2011 by ECE, UofA

Color Coding Used in Edit Window

• Comments displayed in green

• Variables and numbers displayed in black

• Complete character strings displayed in magenta

• Incomplete character strings displayed in red

• MATLAB keywords displayed in blue

MATLAB Desktop

ENCMP

100

27©2011 by ECE, UofA

MATLAB Search Path

• MATLAB has a search path that it uses to find M-files.

• M-files are organized in directories on your file system.

• If you enter a name in the Command Window, MATLAB interpreter attempts to find the name as follows:

• Looks for a name as a variable – if it is the case, its content

(value) is displayed

• Checks to see whether the name is an M-file in the current

directory – if it is, MATLAB executes that function

• Checks to see whether the name is an M-file in any directory in

the search path – if yes, MATLAB executes it

MATLAB Desktop

ENCMP

100

28©2011 by ECE, UofA

MATLAB Search Path – NOTE

If you define a variable with the same name as a

MATLAB function or command, that function or command becomes inaccessible (because MATLAB checks for variable names first).

NEVER:use a variable with the same name as a MATLAB function or command

NEVER:create an M-file with the same name as a MATLAB function or command

Use the command which to find which file is being

executed and where is located.

MATLAB Desktop

12

Page 13: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

29©2011 by ECE, UofA

Figure Window

MATLAB Desktop

• It is used to display MATLAB graphics.

• It can be a two- or three-dimensional plot of data, an

image, or a graphical user interface (GUI)

ENCMP

100

30©2011 by ECE, UofA

Figure Window

MATLAB Desktop

ENCMP

100

31©2011 by ECE, UofA

More on Figure Windows

• MATLAB can create multiple figure windows.

• The first window will be called "Figure 1"

• The second window will be called "Figure 2”, etc.

• The figure number increases automatically by 1 each time a new figure window is created.

• The figure(x) command causes "Figure x" to

be the current figure window, which will be used

for the next plotting command.

• The contents of the current figure window can be cleared using the clf command.

MATLAB Desktop

ENCMP

100

32©2011 by ECE, UofA

MATLAB Workspace

• When a variable is created, and a value is assigned to it, the variable is saved in a part of computer memory called workspace.

• Workspace is a collection of all variables and arrays that can be used by MATLAB when a particular command, M-file, or function is executed.

• All commands executed in the Command Window share a common workspace, so they can all share

variables.

• A list of the variables and arrays in the current

workspace can be generated with the command whos. Another way of doing it is with a GUI …

MATLAB Desktop

13

Page 14: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

33©2011 by ECE, UofA

Access to the Workspace Browser

MATLAB Desktop

ENCMP

100

34©2011 by ECE, UofA

Display current value of variable2) The Variable/Array Editor pops up

MATLAB Desktop

1) Double-click a variable

ENCMP

100

35©2011 by ECE, UofA

Using the Variable/Array EditorEdit the variable's value

the new value

MATLAB Desktop

ENCMP

100

36©2011 by ECE, UofA

Running M-file Overwrites the Edit

1) Change radius

2) Run sample01

3) Check radius

MATLAB Desktop

14

Page 15: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

37©2011 by ECE, UofA

Command History Window

• A history of all past commands can be viewed in the Command History Window.

• Past commands can be re-executed by "double-clicking" the command with the mouse.

• The record of a past command can be deleted by "right-clicking" the command, and then selecting "Delete Selection" from the pop-up menu.

MATLAB Desktop

ENCMP

100

38©2011 by ECE, UofA

Current Directory Window

• The Current Directory window shows the contents (subfolders and files) that are in the currently active MATLAB directory.

• The current directory can be changed by double-clicking either the parent directory symbol (the up arrow button) or one of the subfolder icons.

• Double-clicking a file name will cause the file to be opened in a pop-up editor window.

MATLAB Desktop

ENCMP

100

39©2011 by ECE, UofA

MATLAB Start Button

The "Start" button is a general entry point to all MATLAB

windows, desktop tools, help files, Toolboxes, Simulink, etc.

MATLAB Desktop

ENCMP

100

40©2011 by ECE, UofA

“?” Button for the Help Browser

MATLAB Desktop

15

Page 16: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

02_MATLAB ENVIRONMENT

ENCMP

100

41©2011 by ECE, UofA

"lookfor" to Find Info about Commands

MATLAB Desktop

ENCMP

100

42©2011 by ECE, UofA

Other Useful MATLAB commands (1)

• The demo command provides tutorial demonstrations

of how to use MATLAB.

• The clc command clears the Command Window.

• The clf command clears the Figure Window.

• The clear command clears the workspace variables.

This command is useful to ensure that each new execution of a program is not affected by variables that might have been loaded by earlier commands or M-files.

MATLAB Desktop

ENCMP

100

43©2011 by ECE, UofA

Other Useful MATLAB commands (2)

• Control+c (simultaneously type the Ctrl and C keys)

is used to abort execution of a run-away program.

• The diary filename command causes all typed

commands to be saved in a file named "filename".

• The diary off command suspends input to the diary

file.

• The diary on command resumes input to the diary

file.

MATLAB Desktop

16

Page 17: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

MATLAB Basics – Part I

ENCMP 100

2©2011 by ECE, UofA

Overview

• Basic structure of a MATLAB program

• Arrays and variables

• Basic plotting

• Data types

• Basic input/output

MATLAB Basics I

ENCMP 100

3©2011 by ECE, UofA

A simple MATLAB program

A MATLAB script is also called a M-file:

% plot_sin.m: This M-file calculates and plots

% the function sin(x) for 0<=x<=6

clear; clc

x = 0:0.1:6;

y = sin(x);

plot(x, y)

Header: each comment line begins with % and ends at the end of the line, showing the file name, and/or a list of variables

a MATLAB variable with user defined name. It can be assigned values using arrays. Here x is defined as a row vector, containing values from 0 to 6 with an increment of 0.1 at each time.

Use the MATLAB build-in function to generate another variable

Plot y vs. x. MATLAB can generate 2 or 3 dimensional plot of data or an image.

clean up the work space, delete all existing variables

MATLAB Basics I

ENCMP 100

4©2011 by ECE, UofA

MATLAB program structure

MATLAB is also a computer program other than a scratch

pad or math calculator. It can handle many sophisticated jobs by implementing its own programming language.

Normally a program contains at least the following 4 elements.

Initialization of variables, loading/inputting data

Main part: manipulation on the variables using the built-in functions

Header, e.g. a comment line showing the file name, the author, and/or a list of variables defined in the program

Plotting end results, outputting/saving data

See the assignment for example

MATLAB Basics I

17

Page 18: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

5©2011 by ECE, UofA

In MATLAB, data are stored by using scalars, vectors and

matrices, which are collectively called arrays. The primary kind of data in MATLAB is the array.

• An array is a collection of data values organized into rows and columns and known by a name. Arrays can be scalars, vectors or matrices.

• A scalar is a one-by-one array.

• A vector is equivalent to a one-dimensional array.

• A matrix is equivalent to a two-dimensional array.

Data in MATLAB: arrays

MATLAB Basics I

ENCMP 100

6©2011 by ECE, UofA

• The size of an array is specified as:

the number of rows x the number of columns

• The function size()is used to display the dimension

of the array.

• In an array, the number of elements in each row must be the same and the number of elements in each column must be the same.

Data in MATLAB: arrays

MATLAB Basics I

ENCMP 100

7©2011 by ECE, UofA

Data in MATLAB: arrays>> a = 10 >> b = [1 2 3 4]

a = b =

10 1 2 3 4

>>size(a) >>size(b)

ans = ans =

1 1 1 4

>> c = [3;5;7;9] >> d = [1 2 3; 4 5 6]

c = d =

3 1 2 3

5 4 5 6

7 >>size(d)

9 ans =

>>size(c) 2 3

ans =

4 1

The size of this scalar-valued variable is 1 x 1

The size of this vector-valued variable is 1 x 4

The size of this matrix-valued variable is 2 x 3

The size of this vector-valued variable is 4 x 1

MATLAB Basics I

ENCMP 100

8©2011 by ECE, UofA

Data in MATLAB: arrays

Each element in an array can be represented by the

array name and the row and/or the column of this element. For example, an element in a vector or a matrix array is represented by

vectorname(i) or matrixname(i,j)

In the previous slide, b(2) = 2, c(3) = 7, d(2,2) = 5

Each row or column of a matrix is specified by the column or row number in the following way:

d(1,:)=

1 2 3

d(:,1)=

1

4

d(1,:)represents the first row of the matrix d

d(:,1) represents the first column of d

MATLAB Basics I

18

Page 19: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

9©2011 by ECE, UofA

Data in MATLAB: arrays

• We can also combine different arrays to create a new one, e.g.

>> e = [b(2) c(3) d(2,2)]

e =

2 7 5

>> f = [e d(1,:)]

f =

2 7 5 1 2 3

• An empty array can be created as >> x = []

MATLAB Basics I

ENCMP 100

10©2011 by ECE, UofA

MATLAB variables and data types

A MATLAB variable is a region of memory containing an array, e.g. a, b, c, d, etc. shown in the previous

slides.

Before using any variable in the code, we must decideand specify which data type to associate it with. The data type tells the compiler how to create a particular chunk of memory:

• How big it should be

• How the data it contains should be formatted

• How the data can be manipulated

MATLAB Basics I

ENCMP 100

11©2011 by ECE, UofA

MATLAB variables and data types

Variable names:

• MATLAB is case sensitive so the upper and lower case letters are not treated the same.

• Use descriptive names, e.g. my_id, interest_rate,

time

• Make sure the variable name is unique in the first 63 characters.

• Never use space in the variable name, use the underscore _ to separate words.

• Never use the same name as that of the MATLAB built-in functions or the predefined constants, e.g. pi, clock,

date, ans, etc.

MATLAB Basics I

ENCMP 100

12©2011 by ECE, UofA

Basic plotting in MATLAB

One of the most attractive features of MATLAB is its

extensive and powerful plotting functions. It makes the analysis and design using MATLAB more intuitive and convenient.

MATLAB can handle very sophisticated plotting and

imaging tasks.

First, we introduce some basic plotting functions. Later, we will introduce more advanced plotting and imaging functions whenever needed.

MATLAB Basics I

19

Page 20: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

13©2011 by ECE, UofA

Basic plotting

The most commonly seen graphs in science and engineering are the x-y plots, where y=f(x) (in most cases).

For two vectors x and y of the same length, the MATLAB function plot(x,y) generates the plot of the vector yversus the vector x. For example,

x=[1 2 3 4 5 6 7 8 9 10];

y= exp(x);

plot(x,y)

A figure window automatically opens after the plot

function is executed. One can also manually open a figure window by typing in figure.

MATLAB Basics I

ENCMP 100

14©2011 by ECE, UofA

Basic plotting: a MATLAB figure

The default color for a single line is blue, and the default line style is ‘solid’.

The x axis

The y axis

MATLAB Basics I

ENCMP 100

15©2011 by ECE, UofA

Basic plotting

A plot with more than one line (curve) can also be

created. One way to do this is the following

plot(x1, y1, x2, y2, x3, y3…)

where the vector arrays x1, y1 form the first ordered set of values to be plotted, the arrays x2, y2 form a second

ordered set of values to be plotted, and so on.

MATLAB will automatically assign default colors to different lines if not specified by the user. The default line style is solid.

MATLAB Basics I

ENCMP 100

16©2011 by ECE, UofA

Basic plotting

If one of x and y is a matrix, the function plot(x,y)

plots the vector versus the rows or the columns of the

matrix (whichever lines up with the vector). It will generate multiple lines/curves.

For two matrices x and y, the function plot(x,y)

plots the rows or columns of one matrix versus the rows or columns of the other matrix whichever lines up. It will generate multiple lines/curves.

The function plot(x) (with only one argument) will plot the vector x versus its index. If x is a matrix, it will plot

the columns versus their indices.

MATLAB Basics I

20

Page 21: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

17©2011 by ECE, UofA

Basic plotting

MATLAB can create multiple sub-plots in one figure.

The function subplot(m,n,i) divides the figure window

into m-by-n small areas, with each one dedicated to a

subplot, and then creates the i-th subplot as the current plot, e.g. subplot(2,2,i), i=1,2,3,4 creates the

subplots in the following order:

1 2

43

MATLAB Basics I

ENCMP 100

18©2011 by ECE, UofA

Basic plotting

One can customize a basic plot figure by choosing different line styles/colors and by altering the plotting range, labeling the axes, adding the figure title and the legend.

Choose different line color and/or line style:

plot(x1,y1,‘Line_opt1’,x2,y2,’Line_opt2’)

Line_opt is a string specifying the line color and style, it

can be one indicator either for the color or the line (mark)

style, or a combination of the two indicators for both line(mark) style and the color.

MATLAB Basics I

ENCMP 100

19©2011 by ECE, UofA

Basic plotting

plot(x1, y1, ‘r-’,x2, y2, ‘b--’)

Here the first line plotting y1 vs. x1 is a red solid line,

while the second one plotting y2 vs. x2 is a blue dashed

line.

A table showing the colors, the line and mark styles is given in the next slide.

MATLAB Basics I

ENCMP 100

20©2011 by ECE, UofA

Basic plotting

Table. Line, Mark and Colour Options

Line Type Indicator Point Type IndicatorColour Indicator

solid - point . blue b

dotted : circle o green g

dash-dot -. x-mark x red r

dashed -- plus + cyan c

star * magenta m

square s yellow y

diamond d black k

triangle

down

v

triangle up ^

triangle left <

triangle

right

>

pentagram p

hexagram h

MATLAB Basics I

21

Page 22: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

21©2011 by ECE, UofA

Basic plotting

The following functions are useful for further editing the figure:title(‘title_string’) add a title to the figure

xlabel(‘string’) add a label to the x-axis

ylabel(‘string’) add a label to the y-axis

grid, grid off add or cancel the grid lines

text(x0,y0,‘text_string’) add a textbox in the plot at

the coordinates (x0,y0)

legend(‘string1’,‘string2’,…) add a legend to the

graph

the legend shows a sample of the line, and lists

the specified string

One can also choose where to put the legend in the figure by using Legend(‘string1’,…,’Location’,LOC)

where LOC is a string such as ‘North’ (top of the figure), ‘South’ (bottom), ‘NorthWest’ (top-left), ‘NorthEast’(top-right). Use help legend to find out more.

MATLAB Basics I

ENCMP 100

22©2011 by ECE, UofA

Example 3.1: plotting

Create the x-y plots for the following data given in the table:

No. Score

1 58.5

2 63.8

3 64.2

4 67.3

5 71.5

6 88.3

7 91.0

8 96.5

9 89.5

10 90.4

Let x = no., y= score, plot y vs. x, 2y vs. x and 0.5y vs. x on the same figure.

Add the figure title, x and y labels. Use different line styles to differentiate the lines and add the

legend.

MATLAB Basics I

ENCMP 100

23©2011 by ECE, UofA

Example 3.1%plot_ex.m, demonstration of basic plot function and others

clear, clc

%close all existing figures

close all

x=1:1:10;

y=[58.5 63.8 64.2 67.3 71.5 88.3 91.0 96.5 89.5 90.4];

y1=2*y;

y2=0.5*y;

plot(x,y,'ko--',x,y1,'r:',x,y2,'b-.')

figure(1)

%this is to choose the current figure to edit (only one here)

%useful if you open multiple figures

title('an example of x-y plot')

xlabel(‘No.')

ylabel(‘Score y, y_1, y_2')

legend(‘Score y',‘Score y1', ‘Score y2','Location','NW')

MATLAB Basics I

ENCMP 100

24©2011 by ECE, UofA

Example 3.1

MATLAB Basics I

22

Page 23: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

25©2011 by ECE, UofA

Basic plotting

For most of the x-y plots, the x-axis and y-axis are equally spaced. So we call these plots linear plots or rectangular

plots. Often in engineering problems, we use the logarithmic sale on one or both of the axes, i.e. log10x or

log10y. These plots are called logarithmic plots.

The function for creating these plots are:semilogx(x,y) plot of y vs using logarithmic scale for x

and linear scale for y

semilogy(x,y) plot of y vs x using linear scale for x and

logarithmic scale for y

loglog(x,y) plot of y vs x using logarithmic scales for

both axes

MATLAB Basics I

ENCMP 100

26©2011 by ECE, UofA

Example 3.2*

The famous Moore’s law (Gordon Moore: co-founder of the Intel Corp.) states that that the number of transistors that fit in per square inch on a semiconductor integrated circuit doubles every two years.

In year 1971, the number is 2300, hence the transistor density since year 1971 can be predicted by

Let t =0 for year 1971 and t=40 for year 2011, use this model to calculate the predicted transistor density for 40 year from 1971 to 2011. Use the subplot function, plot the data in a

linear x-y plot, semilog x plot, semilog y plot and loglog plot.

*: H. Moore, MATLAB for Engineers, 2009, Prentice Hall.

)2/(22300)( ttd ×=

MATLAB Basics I

ENCMP 100

27©2011 by ECE, UofA

%logplot_ex.m: plot transistor no.

%predicted from Moore's law

clc;clear;

close all

t=0:2:40;

year=t+1971;

d=2300*2.^(t/2);

%subplot1: linear plot

subplot(2,2,1);

plot(year, d)

title(' linear plot')

xlabel('year');ylabel('Number')

the array power .^ is used here since t is a vector

%subplot2: semilog x plot

subplot(2,2,2);

semilogx(year,d);

title('semilogx plot')

xlabel('year');ylabel('Number')

%subplot3: semilog y plot

subplot(2,2,3);

semilogy(year,d);

title('semilogy plot')

xlabel('year');ylabel('Number')

%subplot4: loglog y plot

subplot(2,2,4);

loglog(year,d);

title('loglog plot')

xlabel('year');ylabel('Number')

Example 3.2

MATLAB Basics I

ENCMP 100

28©2011 by ECE, UofA

Example 3.2

When using linear scale for the y axis (i.e. the number), it is very hard to read these numbers because they are so much smaller compared to that of later years! Using logarithmic scale for y-axis solves this problem. This is why logarithmic plots are useful, esp. for plotting data that change exponentially.

What you think: why the lines in the semilogy and loglog plots are straight ?

One can add more ticks on the y-axis by using the built-in edit tool of the figure window.

Built-in plot Edit tool. Click to turn it on or off .

MATLAB Basics I

23

Page 24: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

29©2011 by ECE, UofA

Basic plotting

Besides the basic x-y plots, other popular forms of

reporting data are bar graphs, pie charts.

In addition, the histogram, a special type of plot showing the distribution of a set of values, is especially useful in statistical data analysis.

All of these graphs can be easily created in MATLAB.

MATLAB Basics I

ENCMP 100

30©2011 by ECE, UofA

A list of function for creating 2-dimensional charts and

graphs:

bar(x) Generate a vertical bar graph of the vector

x versus its element index. If x is matrix, it groups data by row and generates a group of vertical bars.

pie(x) Generates a pie chart with each element in

x is represented as a slice of pie.

Basic plotting

MATLAB Basics I

ENCMP 100

31©2011 by ECE, UofA

hist(x) Generates the histogram. It computes and

plots the number of the values of x falling into 10 bins (default) that are equally

spaced between the minimum and maximum values.

Basic plotting

MATLAB Basics I

ENCMP 100

32©2011 by ECE, UofA

Basic plotting

MATLAB can also handle 3-dimensional plotting and

imaging.

For example, the function plot3 generated the x-y-z plot, an analogy of plot()in 3D.

Furthermore, the 3D plotting functions in MATLAB can generate more advanced 3D (colored) plots, such as surface, mesh, contour etc., by simply using the functions, surf, mesh, and contour.

We will find out more about these functions later in the course.

MATLAB Basics I

24

Page 25: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

33©2011 by ECE, UofA

Basic plotting

MATLAB is very user friendly dealing with figures. The

plots and graphs may be saved as the MATLAB figure file, with the extension .fig, which can only be opened in

MATLAB;

Also, MATLAB can export the figure plots as graphic images, such as EPS, JPEG, TIFF and PNG formats. This can be done by using the print function:

print <options> file_name

print options (<options>):

-deps create encapsulated postscript image

-djpeg create a JPEG image

-dtiff creates a compressed TIFF image

-dpng create a portable network graphic color image

MATLAB Basics I

ENCMP 100

34©2011 by ECE, UofA

Basic plotting

We can also save or copy the figure file directly from the

figure window:

MATLAB Basics I

ENCMP 100

35©2011 by ECE, UofA

MATLAB data types

(Ref. Fig. 10.2, MATLAB for Engineers, 2nd ed., H. Moore, 2009, Prentice Hall)

Types of Data Stored in MATLAB Matrices

NumericCharacter LogicalSymbolic Objects -

Symbolic Toolbox

Integer Floating Point

multiple signed

integer types

multiple unsigned

integer types

single precision

double precision

complex real

MATLAB Basics I

ENCMP 100

36©2011 by ECE, UofA

Bits and bytes

To store information in computers, it needs storage space in memory.

• bit: binary digit, a variable that only takes two distinct values, 0 or 1 (like ‘on’ and ‘off’ position of a switch). It is the smallest unit in the storage of a digital device.

• byte: 8 bits

• Each number stored in the computer takes different number of bits or bytes depending on its type.

bit 1

0 or 1

bit 2

0 or 1

bit 3

0 or 1 ……bit 8

0 or 1

1 byte

MATLAB Basics I

25

Page 26: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

37©2011 by ECE, UofA

Binary, decimal representations

All information in computers are stored numerically in a series of 0 and 1, called a binary (base-2) representation. It can be easily converted to a decimal (base-10) number. Here is a table showing what the decimal number is represented using binary code in one

byte:

binary decimal binary decimal

00000000 0 00000101 500000001 1 00000110 600000010 2 00000111 700000011 3 00001000 8

00000100 4 ……

MATLAB Basics I

ENCMP 100

38©2011 by ECE, UofA

Standard code in computers (ASCII)

The American Standard Code for Information Interchange (ASCII) is a standard seven-bit code that was proposed by ANSI (American National Standards

Institute) in 1963.

It contains decimal numbers ranging from 0 to 127 (so a total of 128 numbers). These numbers are assigned to letters, numbers, special characters and punctuation marks.

Data in ASCII code can be shared among many different computers operating different software packages.

MATLAB Basics I

ENCMP 100

39©2011 by ECE, UofA

Standard code in computers (ASCII)

MATLAB Basics I

ENCMP 100

40©2011 by ECE, UofA

Numeric data typesFloating-Point: a data type for representing with decimal numbers

• The function double() specifies the double-precision

floating-point numbers (defined by IEEE Standard 754), the MATLAB default type for numeric data.

• For such type of data, each number requires 8 bytes (i.e. 64 bits) of the computer storage space,

• It can hold real or complex values with 15 to 16 significant decimal digits of accuracy, e.g.

x = 3.141592653589793 y = 2.678+7.235i

16 bytes is needed to store a complex number since it has both the real and imaginary components

MATLAB Basics I

26

Page 27: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

41©2011 by ECE, UofA

Numeric data types

• We need to make sure that the assigned number is

within the range of the floating number, otherwise MATLAB will treat it as +inf or –inf.

The realmax and realmin functions give the maximum and the minimum values of a positive double-precision floating-point number.

>> realmax >>realminans = ans =

1.7977e+308 2.2251e-308

So the real number represented in double precision in MATLAB has a range of

(-1.7977x10308, 1.7977x10308)

For a number whose absolute value is smaller than the value specified by realmin, MATLAB will treat it as 0.

MATLAB Basics I

ENCMP 100

42©2011 by ECE, UofA

Numeric data types• The function single()specifies the single-precision

floating-point numbers. It uses half of the storage space of a number of double-precision, i.e. 4 bytes (32 bits).

Use realmax(‘single’) and realmin(‘single’) to find out the range of a positive real number of single-precision in MATLAB, they are

3.4028e+038 and 1.1755e-038

• Compared to the double-precision numbers, single-precision numbers make the calculation faster but normally result in greater round off errors.

• Today’s computers have plenty of storage room (memory) and are extremely fast – it is generally not necessary to use single precision data type in most engineering problems.

MATLAB Basics I

ENCMP 100

43©2011 by ECE, UofA

Numeric data typesInteger: used to represent positive or negative integer numbers or 0. • MATLAB can store different types of integers. They

differ only in how much storage space is allocated and whether the values are signed or unsigned

• Functions: int8 ı int16ı int32 ı int64

(signed integers of 8, 16, 32, 64 bits)uint8, uint16, uint32, uint64

(unsigned integers of 8 16, 32, 64 bits)

For the signed integer numbers, one bit is used to store the sign. The function intmax() and intmin() is used to determine the range of the integer value.

MATLAB Basics I

ENCMP 100

44©2011 by ECE, UofA

Numeric data types

• Data of different numeric type may be combined in the math operation e.g. +, -, *, /, .*, ./, etc.

When there are variables of both double and single precision

types in these math operations, the result is in single precision.

Integers cannot be combined with the values of single precision

type, or even different type of integers. One exception is that

scalar values of double precision can be combined with the

integers in the math operation.

In the above math operations, .* and ./ are the so called array

multiplication and array division. a.*b denotes element-by-element multiplication, and a./b the element-by-element division.

For a=[a1 a2 … an],b=[b1 b2 … bn], a.*b=[a1b1 a2b2 …

anbn], and a.*b=[a1/b1 a2/b2 … an/bn]. a and b must have

the same dimensions unless one of them is scalar.

MATLAB Basics I

27

Page 28: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

45©2011 by ECE, UofA

Example 3.3Enter the following matrix

into arrays of the following numeric data types:• array A, double precision floating point number• array B, single precision floating point number• array C, 8-bit signed integer number• array D, 16-bit unsigned integer number• create a new matrix E by E=A+B, what data type

is the result?• can you add C and D to create a new matrix?

2596

2163

851

MATLAB Basics I

ENCMP 100

46©2011 by ECE, UofA

Example 3.3Enter at the MATLAB command prompt:

>> A = [1 5 8;3 6 12;6 9 25];

>> B = single([1 5 8;3 6 12;6 9 25]);

>> C = int8([1 5 8;3 6 12;6 9 25]);

>> D = uint16([1 5 8; 3 6 12;6 9 25]);

>> E = A+B;

Check the workspace (or use whos at the command prompt), where the information of the variables are shown:

In basic math operations, e.g. + , -, *, /, etc.when there are variables of both double and single types, the result is in single precision.

MATLAB Basics I

ENCMP 100

47©2011 by ECE, UofA

Example 3.3

MATLAB Basics I

Now we try to add C and D to create a new matrix, say F>> F = C+D

Here is the result:??? Error using ==> plus

Integers can only be combined with integers

of the same class, or scalar doubles.

The reason we get this error message is because C and D are different types of integer-valued matrices, even though they are both integer-valued. But the following operation is legal:

>>C+5.2

ans =

6 10 13

8 11 17

11 14 30

5.2 is rounded down to 5 and added to each element of the matrix and the result is in int8type, as same as C

ENCMP 100

48©2011 by ECE, UofA

Example 3.4

MATLAB Basics I

Define x = 1 as an integer type, and y = 3 of the same integer type, calculate x/y in MATLAB? Try again with x = 2?

>> x=int8(1); y=int8(3);

>> x/y

ans =

0

>>x=int8(2);

>>x/y

ans =

1

The result of this math operation should be an integer of type int8.

x/y = 1/3 is rounded to 0 in this case because 0.333<0.5

x/y=2/3 is rounded to 1 because 0.667>0.5, 0.5 will also be rounded to 1

28

Page 29: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

49©2011 by ECE, UofA

Character and string data

MATLAB Basics I

Character array: used to store character information in MATLAB. • Use single quote ‘’ to identify a character string. Each

letter (including space) is treated as an element in the array. The function char specifies the data type as

character.• Conversions can be made between characters and

numbers – all information in computers are stored numerically (e.g. ASCII code). Each character actually has a binary representation and an equivalent decimal (base-10) number. For example, based on the ASCII:

>> double(‘a’) >> char(98)

ans = 97 ans = b

ENCMP 100

50©2011 by ECE, UofA

Character and string data

MATLAB Basics I

• When creating a vector or matrix containing both

numbers and characters, MATLAB converts all data to character information>> [‘a’ 98]

ans =

ab

• When performing math operations with both numeric and character data, MATLAB converts the character data to its numeric equivalent:>> ‘a’+100

ans =

197

ENCMP 100

51©2011 by ECE, UofA

Logical data

MATLAB Basics I

Logical array: containing values 1 and 0 to denote True and False,respectively.

>> L = [true false]

L =

1 0

>> A=10; B=100;

>> D = A>B

D =

0 (it means false)

The function logical() converts an array of real numeric values

into a logical array. It treats any non-zero real numbers as true 1 and zero as false 0. For example, the statement

>> L = logical([1.2 0 -0.1 -2])

returns [1 0 1 1]

In this operation, D is a logical array, its value is 0 or 1depending on whether the statement “A>B” is true or not.

ENCMP 100

52©2011 by ECE, UofA

Basic input/output

The input/output capability of the computers makes

information interchange possible.

Every computer language has its own input/output commands (functions) to read data, open the data file, and write out data.

Here we introduce two basic I/O functions in MATLAB:• input

• disp

MATLAB Basics I

29

Page 30: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

53©2011 by ECE, UofA

The `input( )’ function:

• It displays a prompt string in the command window

during execution of the program, waiting for the user to type in the requested input.

ini_val = input(‘Enter an input’)

During execution, MATLAB displays a text string in the command

window:

Enter an input:

Then ini_value = 5 or a matrix 1 2 3 or a string ‘smith’

4 5 6

type in a number, e.g. 5, or an array enclosed in brackets, e.g. [1 2 3; 4 5 6], or even a string, e.g. ‘smith’

MATLAB Basics I

Basic input/outputENCMP

100

54©2011 by ECE, UofA

Basic input/output

• The user input typed at the prompt can be directly stored as a character string, if the input function has ‘s’ as a second argument.

>>in_resp = input(‘Enter response: ’, ‘s’)

Enter response: Yes

then in_resp = ‘Yes’, or ‘100’, i.e. a string type,

even if a number is given at the prompt.

or a number , say 100

MATLAB Basics I

ENCMP 100

55©2011 by ECE, UofA

The `disp( )’ function:

• It is a simple function to display the contents of an

array, which can be used to output the final results.>>A = 1:1:5;

>>disp(A)

returns

1 2 3 4 5

in the MATLAB command window, without showing the variable

name.

• It is different from the MATLAB command echoing when a semicolon is absent. In the latter case, the variable name is shown, e.g. A = 1:1:5 returns

>>A =

1 2 3 4 5no semicolon ‘ ;’

MATLAB Basics I

Basic input/outputENCMP

100

56©2011 by ECE, UofA

• Use the function disp to make the output display more

user friendly:

N= 100;

disp(‘The number of students is: ’)

disp(N)

returns

The number of students is:

100

or we can display them in a single line like this,

disp([‘The number of students is ’ num2str(N)])

it returns

The number of students is 100

Here we formed a string array of size 1x2

MATLAB Basics I

Basic input/output

30

Page 31: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

03_BASICS - PART ONE

ENCMP 100

57©2011 by ECE, UofA

Example 3.5We can use the functions input and disp together to create fun user-

computer interface, like a conversation.

% test_conv.m: using input() and disp() to mimic a

% computer/user conversation

clear; clc;

disp('Hello!');

disp('I am your MATLAB program');

name = input('Who are you?', 's');

disp(['Hi ', name]);

ans1 = input('Do you like MATLAB so far?', 's');

disp ([ans1, '?']);

disp ('MATLAB is a very useful program language.');

disp ('Good luck with your course! Bye!')

MATLAB Basics I

ENCMP 100

58©2011 by ECE, UofA

Example 3.5

Here is the result:

MATLAB Basics I

ENCMP 100

59©2011 by ECE, UofA

Summary … of covered topics

• Basic structure of a MATLAB program

header, initialization, main part, plotting and output

• Arrays and variables

• Basic plotting functions and tools (with more to come

in future lectures)

• Data types and variables

floating-point (single, double), integer, character, logical

• Simple input/output commands

input(), disp()

MATLAB Basics I

31

Page 32: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

MATLAB Basics – Part II

ENCMP 100

2©2011 by ECE, UofA

Overview

• Simple file I/O commands

• Built-in functions

• Arithmetic operators

• Creation of variables

• Debugging

• Sub-arrays and multi-dimensional arrays

MATLAB Basics II

ENCMP 100

3©2011 by ECE, UofA

We will learn how MATLAB handles data files because

very often we need to load or save data in programming.

• Special data file format in MATLAB: the MAT file

.mat file is the default type that data files are saved in MATLAB. We will need MATLAB to process .mat file.

• To share data among different programs, we need to specify the –ascii option when saving or loading the

data

• Basic data file functions:• save

• load

MATLAB Basics II

Basic input/output (I/O) functionsENCMP

100

4©2011 by ECE, UofA

The `save()’ function:

It saves data from the current MATLAB workspace to a file.

• A general form:save(‘file_name’, ‘var1’, ‘var2’)

It saves one or more variables (e.g. var1, var2,…) in a file with the name specified by the file_name string (a string containing the

file name and/or the path). By default, the file name will be given

a MAT file extension .mat if it has no other extension specified.

• To save in the more general ascii data format, use

save(‘file_name.dat’,‘var’,‘-ascii’)

It is suggested to add the .dat extension to the file name in this case

to differentiate from the .mat file.

Use single quotation marks because the arguments are strings!

Basic data file processing functions

MATLAB Basics II

32

Page 33: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

5©2011 by ECE, UofA

• The save function can also be executed in a

command form,

save file_name var1 var2 or

save file_name.dat var1 var2 -ascii

Different from the save() function, there are no single quotation

marks for the file name and the variable in this command form.

They are simply separated by space. Therefore, in the case when

the file name contains one or more spaces, this command form

cannot be used, e.g.

save my file x y z (wrong! It’ll treat file as one variable to be saved)

save my_file x y z (correct!)

or write

save(‘my file’, ‘x’, ‘y’, ‘z’) (correct!)

Basic data file processing functions

MATLAB Basics II

ENCMP 100

6©2011 by ECE, UofA

The `load()’ function:

• It loads data from a disk file to the current MATLAB workspace. A general format is shown below:

load(‘file_name’)

It loads all variables saved (e.g. var1, var2, var3) in the file

with the name specified by the file_name string. If the file

name has no extension, by default MATLAB will treat it as a MAT

file. It is also possible to load specified variables in the file:

load(‘file_name’, ‘var1’, ‘var2’)

• To load an ASCII data file, use:

load(‘file_name.dat’)

• Use –mat or –ascii options:

load(‘myfile.dat’, ‘-mat’)

load (‘myfile.mat’, ‘-ascii’)

Basic data file processing functions

MATLAB Basics II

ENCMP 100

7©2011 by ECE, UofA

• Just like save function, the load function has a

command form:

load format file_name var1 var2 ..

e.g.

load –mat test.dat

load –ascii test.mat

load test.mat x y

Basic data file processing functions

MATLAB Basics II

ENCMP 100

8©2011 by ECE, UofA

MATLAB built-in functions

MATLAB is best known by its powerful variety of built-in functions ready to use to solve complex scientific and

engineering problems.

• One way to find out and explore these built-in functions is to use the MATLAB help browser or simply type help in

the command window. It will display a directory of many different subjects/topics in math, statistics, and engineering.

• To learn more about a specific function, we can type help function_name or doc function_name at

the command prompt. The doc command brings out the

help browser window where a more complete help menu about the function will be displayed.

MATLAB Basics II

33

Page 34: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

9©2011 by ECE, UofA

MATLAB built-in functions

• Many MATLAB functions take inputs as arrays (vectors or matrices) and generate outputs as arrays.

For example, the following simple script calculates the output y as a

function of time t, y = e-2t sin(2πt). It produces an array of output values from 0 to 2 (sec.) for every 0.1 (sec.)

t = 0:1:20;

size(t)

y = exp(-2*t)*sin(2*pi*t);

size(y)

This returns

ans =

1 21

ans =

1 21

The size command returns the dimension of the array. For both vectors t and y, the size is 1x21.

MATLAB Basics II

ENCMP 100

10©2011 by ECE, UofA

Some common functions

Common mathematical functions: most MATLAB function names are consistent with those of other computer

languages . Here are some basic ones:•sqrt(x) square root of x

•exp(x) exponential function ex

•log(x) natural logarithm loge x, or ln x

•log10(x) log10 x

•abs(x) |x|, the absolute value of x; it returns

the modulus if x is complex, x=a+bi)

•angle(x) phase angle of the complex number x in radians

•max(x),min(x) find the maximum and minimum

number of the array x

•sum(x) sum of the elements in vector x, for matrix x, it

is a row vector with the sum over each column

22ba +

MATLAB Basics II

ENCMP 100

11©2011 by ECE, UofA

Example 4.1

Compute the distance between two points a, b on a

Cartesian coordinate plane?

The distance between the two points is:

o x

y

b (3, 1.5)

a (-1, 2)

22 )()( baba yyxx −+−

MATLAB Basics II

ENCMP 100

12©2011 by ECE, UofA

Example 4.1

The MATLAB script:%compute the distance between two points a(-1,2) %and b(1.5,3)

x_a=-1;y_a=2;

x_b=3; y_b=1.5;

dist=sqrt((x_a-x_b)^2+(y_a-y_b)^2)

This returns >>dist =

4.0311

Can you think of another way to get the answer? Here is one:%define two complex values for the two points

a=-1+2i;b=3+1.5i;

%the distance of the two points is the modulus

%of the complex number (a-b)

dist=abs(a-b))

MATLAB Basics II

34

Page 35: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

13©2011 by ECE, UofA

Example 4.2

Compute the following quantity in both double and single precision values for m=1000 and m=107

Obviously, when m is a big number, it is not possible to write out one single summation in a program. This kind of operation is

normally done by the so-called iteration in a computer program,

which will be discussed later. Here we take advantage of the

MATLAB built-in functions.

For example, the sum()function is useful in this case. For a big

number m, 1/m has a small value close to zero. In this case,

numerical errors will show and accumulate through the summation,especially when using a data type of shorter memory space, like the

single-precision type.

Q =1

nn =1

m

∑ =1+1

2+

1

3+

1

4+ ...+

1

m

MATLAB Basics II

ENCMP 100

14©2011 by ECE, UofA

%harmonic_series.m: compute a harmonic series

%define double precision numbers

m1=1000;m2=10^7;

%define single-precision numbers

m3=single(m1);m4=single(m2);

%compute 1/n

n_vec1=1:1:m1;n_vec2=1:1:m2;

n_vec3=1:1:m3;n_vec4=1:1:m4;

inv_n1=1./n_vec1;inv_n2=1./n_vec2;

inv_n3=1./n_vec3;inv_n4=1./n_vec4;

%compute the series value

Q1_double=sum(inv_n1);

Q2_double=sum(inv_n2);

Q1_single=sum(inv_n3);

Q2_single=sum(inv_n4);

%create a matrix to display at the prompt for comparison

Q=[Q1_double Q1_single;Q2_double Q2_single]

Example 4.2

MATLAB Basics II

ENCMP 100

15©2011 by ECE, UofA

Example 4.2

This script returns

>>Q =

7.4855 7.4855

16.6953 16.1122

The first row shows the results for both double and single precision when m = 1000, and the second row shows the results for the two types when m = 107.

For m = 1000, the results are the same at least in the first 4 significant decimals. However, when m = 107, the results of

double and single precision are quite different. The usage of

single precision numbers results in big round-off errors in this

case.

MATLAB Basics II

ENCMP 100

16©2011 by ECE, UofA

Some common functions

Trigonometric functions• sin(x) sine of x, x is in radians

• sind(x) sine of x, x is in degree

• cos(x) cosine of x, x is in radians

• tan(x) tangent of x, x is in radians

• asin(x) arcsine of x or sin-1x, x∈ [-1,1]

returns an angle in radians ∈ [-π/2,π/2]

• asind(x) sin-1x, returns an angle in degrees

• acos(x) arccosine of x, cos-1x, x∈ [-1,1]

• atan(x) tan-1x, returns an angle in radians ∈ [-π/2,π/2]

• atan2(x,y) tan-1 (x/y), over all 4 quadrants

MATLAB Basics II

35

Page 36: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

17©2011 by ECE, UofA

Some common functions

When using the trigonometric functions, one needs to

pay particular attention to the unit of the angle since most trigonometric functions take or return angles in radians.

To convert between radians and degrees:

degrees = radians x (180/π) or

radians = degrees x (π/180)

MATLAB Basics II

ENCMP 100

18©2011 by ECE, UofA

Example 4.3

Find out the height of the building, d = 10m, h0=1.8m,

and θ = 70 deg.

By knowing d, θ and h2 ,

the building height can

be calculated as:

)tan(0 θdhh += h

θ

dh0

MATLAB Basics II

ENCMP 100

19©2011 by ECE, UofA

Example 4.3MATLAB script:% build_height.m: estimating height of a building

% create variables

h_0=1.8;

d=10;

theta_deg=70;

%convert degree to radians

theta_rad=theta_deg*pi/180;

%calculate the height

h=h_0+d*tan(theta_rad)

It returns

>> h =

29.2748

MATLAB Basics II

ENCMP 100

20©2011 by ECE, UofA

Some common functions

Rounding functions:

• round(x) round x to the nearest integer

• floor(x) round x to the nearest integer towards minus infinity

• ceil(x) round x to the nearest integer towards plus infinity

• fix(x) round x to the nearest integer towards zero

floor(3.1)=3 floor(-4.1)=-5

ceil(3.1)=4 ceil(-4.1)=-4

round(4.2)=4 round(-4.7)=-5

fix(4.2)=4 fix(-4.2)=-4

MATLAB Basics II

36

Page 37: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

21©2011 by ECE, UofA

Arithmetic operations

MATLAB supports all standard arithmetic operations between scalars. In addition it supports two types of operations between arrays, the so-called array operations

and matrix operations.

Array operations are the element-by-element (scalar) operations between two arrays of the same dimension.

For example, using the array multiplication .* for two arrays a, and b, the resulted array, a.* b, has the same dimension and the

element is calculated as a(i,j)b(i,j).

MATLAB Basics II

ENCMP 100

22©2011 by ECE, UofA

Arithmetic operations

Matrix operations in MATLAB are consistent with the standard matrix computations, such as addition, subtraction, multiplication, and

division.

Unlike the array operations, the arrays in matrix operation should have

compatible dimensions (they may not be the same).

For example, the matrix multiplication of the array a of the dimension

m x p and the array b of the dimension p x n, is defined as:

the number of columns in a should be as same as the number of rows in b.

=×=

),(...)2,()1,(

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

),2(...)2,2()1,2(

),1(...)2,1()1,1(

nmcmcmc

nccc

nccc

bac ),(),(),(1

jkbkiajicp

k

∑=

=

MATLAB Basics II

ENCMP 100

23©2011 by ECE, UofA

Arithmetic operations

Here we summarize the commonly used arithmetic

operations in MATLAB. The standard arithmetic operations between scalars are:

Algebraic operation MATLAB

addition a+b a+b

subtraction a-b a-b

multiplication axb a*b

division a/b a/b

exponentiation ab a^b

MATLAB Basics II

ENCMP 100

24©2011 by ECE, UofA

Arithmetic operations

Array operation:

For two arrays, a, b, of the same dimension, or one of

them as a scalar, the following operations are defined:

Array Operation MATLAB Explanation

array addition a+b element-by-element

addition, a(i,j)+b(i,j)

array subtraction a-b a(i,j) – b(i,j)

array multiplication a.*b a(i,j)*b(i,j)

array right division ./ a./b a(i,j)/b(i,j)

array left division .\ a.\b b(i,j)/a(i,j)

exponentiation a.^b a(i,j)^b(i,j)

MATLAB Basics II

37

Page 38: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

25©2011 by ECE, UofA

Arithmetic operations

Matrix operation:

For two arrays, a, b, of the compatible dimensions, or

one of them as a scalar, the following operations are defined:

Matrix Operation MATLAB Explanation

matrix addition a+b same as array addition

matrix subtraction a-b same as array sub.

matrix multiplication c=a*b

matrix inverse inv(a) a-1, a x a-1 = I,

I: identity matrix

matrix right division / a/b a*inv(b)

matrix left division \ a\b inv(a)*b

∑=

=

n

k

jkbkiajic1

),(),(),(

MATLAB Basics II

ENCMP 100

26©2011 by ECE, UofA

Arithmetic operation ordersWhen combining different arithmetic operations in one equation or expression, their evaluations follow the order of arithmetic operations, summarized in the following

table:

Precedence operations

1 contend in all parentheses, starting from

the innermost one and work outward

2 all exponentiations, working from left to right

3 all multiplications and division, from left to right

4 all additions and subtractions from left to right

MATLAB Basics II

ENCMP 100

27©2011 by ECE, UofA

Example 4.4

Assume that a, b, c, and d are defined as follows:

Are the following MATLAB operations legal? Calculate the results of the ones which are legal.

(i) result = a+b; (ii) result = a*d;

(iii) result = a.*d; (iv) result = a*c;

(v) result = a.*c; (vi) result = a/b

(vii) result = a./b; (viii) result = a.^b;

==

=

−=

−=

10

01)2(,

1

2,

20

31,

41

12eyedcba

MATLAB Basics II

ENCMP 100

28©2011 by ECE, UofA

Example 4.4

(i) legal operation;

(ii) legal operation;

(iii) legal operation;

(iv) legal operation;

(v) illegal operation because 1 and c should be of the same dimension for array operation;

(vi) legal operation;

(vii) legal operation;

(viii) legal operation;

The M file for this example and its result are shown next:

MATLAB Basics II

38

Page 39: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

29©2011 by ECE, UofA

%arithmetic_ex.m, arithmetic

%calculations in MATLAB

clc;clear

a=[2 1;-1 4];

b=[-1 3;0 2];

c=[2;1];

d=eye(2);

%(i)a+b: matrix addition

result = a+b;

disp('(i) result = a+b =')

disp(result)

%(ii)a*d: matrix multiplication

result = a*d;

disp('(ii) result = a*d =')

disp(result)

%(iii)a.*d: array multiplication

result = a.*d;

disp('(iii) result = a.*d =')

disp(result) �

%(iv)a*c: matrix multiplication

result = a*c;

disp('(iv) result = a*c =')

disp(result)

%(vi)a/b: matrix right division

result = a/b;

disp('(v) illegal operation')

disp('(vi) result = a/b =')

disp(result)

%(vii)a./b: array right division

result = a./b;

disp('(vii) result = a./b =')

disp(result)

%(viii)a.^b: array exponentiation

result=a.^b;

disp('(viii) result = a.^b =')

disp(result)

MATLAB Basics II

Example 4.4ENCMP

100

30©2011 by ECE, UofA

Example 4.4

It returns:

Verify your answer.

MATLAB Basics II

ENCMP 100

31©2011 by ECE, UofA

Evaluate each of the following operations:(a)11/5+6

(b)11/5+6*2

(c)11/(5+6)*2

(d)2*2^2^3

(e)2*2^(2^3)

Based on the operation order, the expected answers are

(a)8.2, division first then addition

(b)14.2, from left to right, division and multiplication first and then addition

(c)2, the operation in parenthesis is evaluated first, then division and

multiplication from left to right

(d)128, exponentiation is evaluated first from left to right and then

multiplication

(e)512, the operation in parenthesis is evaluated first, then exponentiation,

followed by the multiplication.

Example 4.5

MATLAB Basics II

ENCMP 100

32©2011 by ECE, UofA

Example 4.5

The answers can be verified by MATLAB

MATLAB Basics II

39

Page 40: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

33©2011 by ECE, UofA

Example 4.6

Solve the following system of linear simultaneous

equations for all the x variables:

Solving linear simultaneous equations can be easily done using MATLAB by converting them to a matrix/vector form.

105634

6546

1252

0352

4321

4321

4321

4321

=−−+

−=−−+−

=−−−

=+++−

xxxx

xxxx

xxxx

xxxx

MATLAB Basics II

ENCMP 100

34©2011 by ECE, UofA

Example 4.6

The following form is equivalent to the 4 simultaneous

equations:

Denote the matrix containing all the coefficients a and the vector containing all x variables to be solved x, and the vector on the right hand side of the equation b, i.e.

ax=b

Then the solution for x is x = a-1 b, where a-1 is the inverse matrix of a.

−=

−−

−−−

−−−

10

6

1

0

5634

5461

2512

3152

4

3

2

1

x

x

x

x

MATLAB Basics II

ENCMP 100

35©2011 by ECE, UofA

Example 4.6%simult_eq.m, solving system of linear equations

clear;clc;

a=[-2 5 1 3;2 -1 -5 -2;-1 6 -4 -5;4 3 -6 -5];

b=[0;1;-6;10];

x=inv(a)*b;

disp('The solutions are:')

disp(['x_1= ' num2str(x(1))]);

disp(['x_2= ' num2str(x(2))]);

disp(['x_3= ' num2str(x(3))]);

disp(['x_4= ' num2str(x(4))]);

It results:

The solutions are:

x_1= 4.1803

x_2= 1

x_3= 0.95082

x_4= 0.80328

MATLAB Basics II

ENCMP 100

36©2011 by ECE, UofA

Example 4.6

In fact, one can use the matrix left division to solve this

problem, since

a\b = inv(a)*b

So using one command x=a\b we can obtain the same

answer!ans =

4.1803

1.0000

0.9508

0.8033

MATLAB Basics II

40

Page 41: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

37©2011 by ECE, UofA

Creating variables in MATLAB

Now with what we’ve learnt so far, we are able to perform

basic programming in MATLAB.

The very first step would be to create variables. As we have seen, in MATLAB, variables are created when they are first initialized:

• Assigning vectors, matrices to variables, e.g.t = 0:0.1:10; omega = 2*pi/t;

vec1 = [1 2 3 4]; x = vec1*vec1’;

Normally in a M-file, we use semi-colon (;) at

the end of variable assignment statement to turn off the value

echoing in the command window.

When using arithmetic operations with vectors and matrices, make

sure the dimensions are compatible.

The single quotation mark ’is the transpose operator of the vector/matrix

MATLAB Basics II

ENCMP 100

38©2011 by ECE, UofA

• Initializing variables using built-in functions

In a program, variables are often assigned to certain initial values

(e.g. zeros or ones) at the time they are created. In MATLAB, the built-in function zeros() is used to assign an array of value 0 to a

variable, while ones() is used to assign an array of value 1. In

addition, the identity matrix of dimension n by n, e.g.

a 4x4 identity matrix

is generated in MATLAB using the function eye(4)

=

1000

0100

0010

0001

I

MATLAB Basics II

Creating variables in MATLAB

ENCMP 100

39©2011 by ECE, UofA

Here are some examples using these functions:

a = zeros(4,5);

b = zeros(3);

c = eye(4);

d = ones(1,5)

e = [1 3 5 7; 2 4 6 8];

f = zeros (size(e))

Can you write out the results?

• Assigning values to variables with keyboard input

This allows a script to prompt a user for input data during execution. The input function is used in this case to display a

string in the command window waiting for the user to type in a

number or string. The response from the user is then passed to the corresponding variable in the script. This option allows the

program to produce the ‘customized’ results and output.

MATLAB Basics II

Creating variables in MATLABENCMP

100

40©2011 by ECE, UofA

A weight problem: how much you weigh on other planets?

In this example, we will show how to write a MATLAB program to calculate your weight on several other planets, e.g. moon, pluto, and mars, and then display the results.

The first portion of the program: where all the variables are created

and assigned pre-determined values.

The second portion: calculate the weight

The last portion: display results

* When programming, try to take advantage of the MATLAB arrays and array operations.

MATLAB Basics II

Example 4.7

41

Page 42: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

41©2011 by ECE, UofA

%weight.m: calculate your weight on other planet

%create variables

clear;clc;

%the acceleration rate due to gravity on earth

g=9.81;

%factors of the acceleration rate on other planets relative to g

f_mars=0.38;

f_moon=0.17;

f_pluto=0.04;

f = [1 f_mars f_moon f_pluto];

%input the weight at the command prompt

w_earth=input('Please input your weight on earth (in kg): ');

%calculate the weight

w=w_earth*f;

%display the result

disp(['your weight on the Earth is (in kg): ' num2str(w(1))]);

disp(['your weight on the Mars is (in kg): ' num2str(w(2))]);

disp(['your weight on the Moon is (in kg): ' num2str(w(3))]);

disp(['your weight on the Pluto is (in kg): ' num2str(w(4))]);

Example 4.7ENCMP

100

42©2011 by ECE, UofA

It returns

Please input your weight on earth (in kg): 60

your weight on the Earth is (in kg): 60

your weight on the Mars is (in kg): 22.8

your weight on the Moon is (in kg): 10.2

your weight on the Pluto is (in kg): 2.4

MATLAB Basics II

Example 4.7

ENCMP 100

43©2011 by ECE, UofA

Basic debugging

After writing a program, one needs to perform the

debugging process, a process for finding and eliminating program errors (bugs). For MATLAB program, there are normally 3 types of errors.

Syntax error: typos, spelling, punctuation errors, or when

you provide the function with inputs that are the wrong shape, size, and/or type; unbalanced or unexpected parenthesis. Some common MATLAB error messages for this type of error are:

??? Undefined function or variable ‘xxx'.

??? CAT arguments dimensions are not consistent.

??? Subscripted assignment dimension mismatch.

Error: Expression or statement is incorrect--

possibly unbalanced (, {, or [.

The mis-matched array sizes or inconsistent dimensions are very common errors in MATLAB!

MATLAB Basics II

ENCMP 100

44©2011 by ECE, UofA

Basic debugging

Runtime error: when an illegal mathematical operation is attempted, e.g. the divide-by-zero case. It causes the program return inf or NaN, which may be used in the

remainder of the program.

Logic error or algorithmic error: when the program executes perfectly, but the result is not what is expected.

Compared to the syntax error, the last two types of errors are relatively hard to detect, especially the logic error may

require careful step by step inspections. In this case, we can utilize some debugging functions/tools of MATLAB and its program (M file) editor.

MATLAB Basics II

42

Page 43: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

45©2011 by ECE, UofA

Basic debuggingHow to locate and find the program bugs?

Set break points in the script to pause execution of the

MATLAB file – so we can examine values at specific locations.

To set break points:

Open the file, click on

the dash of the line at which

you want to set the break

point, the dash becomes

the red dot.

Click again to cancel.

For debugging, it is better to dock the editor to the MATLAB command window.

MATLAB Basics II

ENCMP 100

46©2011 by ECE, UofA

Basic debugging

Step through the file: while debugging, you can step

through a MATLAB file using the following commands.

Step options in the Editor Debug menu

The dbstep or dbcont function in command window.

While debugging, each time you click ‘Step’ or F11, one line will be executed further from the break point.

MATLAB Basics II

ENCMP 100

47©2011 by ECE, UofA

Basic debugging

The following table give the details of these methods:

Source: http://www.mathworks.com/help/techdoc/matlab_env/brqxeeu-175.html

MATLAB Basics II

ENCMP 100

48©2011 by ECE, UofA

More on arrays: subarrays

When storing data in arrays, often we need to manipulate only some data instead of all. In this case, subarrays are

useful.

Subarrays (portions of an array) can be created by selecting subsets of elements in the original array:>>a=0:0.5:3

>>a=

0 0.5 1 1.5 2 2.5 3

>>sub_a1=a(1:2:7)

>>sub_a1=

0 1 2 3

>>sub_a2=a(2:2:7)

>>sub_a2=

0.5 1.5 2.5

The indices in the parentheses indicate how the subset is created. The expression, e.g. 1:2:7, is used here to specify a list of indices. It means choosing one element at every two steps, starting from the first one to the last one in the original vector, so a(1), a(3), a(5) and a(7) are chosen. While for 2:2:7, a(2), a(4) and a(6) are chosen.

MATLAB Basics II

43

Page 44: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

49©2011 by ECE, UofA

Subarrays

We can use the function end in an array subscript, which

returns the highest values taken by that subscript. For the example shown in the previous slide, we can define,

>>sub_a1=a(1:2:end)

>>sub_a1=

0 1 2 3

>>sub_a2=a(2:2:end)

>>sub_a2=

0.5 1.5 2.5

If you do not know the index number of the last element - just use end to represent it.

MATLAB Basics II

ENCMP 100

50©2011 by ECE, UofA

Example 4.8

Create the following matrix array:

then create the following subarrays:

• A1 containing the 1st and the 3rd column;

• A2 containing the last two rows;

• A3 containing the elements in the shaded area

=

1654

6103

5012

4321

A

MATLAB Basics II

ENCMP 100

51©2011 by ECE, UofA

Example 4.8

%subarray.m, create subarrays

clear;clc;

A=[1 2 3 4;2 1 0 5;3 0 1 6;4 5 6 1];

A_1=A(:,1:2:3);

A_2=A(3:4,:);

A_3=A(2:3,2:3);

disp('A_1=')

disp(A_1)

disp('A_2=')

disp(A_2)

disp('A_3=')

disp(A_3)

It returns: �

MATLAB Basics II

ENCMP 100

52©2011 by ECE, UofA

SubarraysIn MATLAB, it is possible to assign values to only a

portion of an array, i.e. a subarray, without affecting the values of the rest of the array. For example,

>>arr1 = [1 2 1 2;3 4 3 4;5 6 5 6]

>>arr1 =

1 2 1 2

3 4 3 4

5 6 5 6

If we want to replace the elements in the shaded area by0 0 , we can use the following statement:0 0

>>arr1(1:2,1:2)=[0 0;0 0]

>>arr1=

0 0 1 2

0 0 3 4

5 6 5 6

We need to make sure that the dimensions of the arrays on both right and left-hand sides are the same! Again, try arr1(1:2,[1 4])=[0 0; 0 0]

See what happens?

MATLAB Basics II

44

Page 45: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

04_BASICS - PART TWO

ENCMP 100

53©2011 by ECE, UofA

Multidimensional arrays

So far we have seen one or two-dimensional arrays (i.e. row or column vectors and matrices). In fact, we can create arrays with more than two dimensions in MATLAB, i.e. the so-called multidimensional arrays.

A three dimensional array can be represented as multiple pages. Each page contains a two

dimensional array.

MATLAB Basics II

ENCMP 100

54©2011 by ECE, UofA

Multidimensional arrays

Higher dimensional arrays can be created in the same fashion. A 4-dimensional array can be represented by multiple ‘books’ (or ‘blocks’) of data, and so on.

An element in the multiple dimensional array is identified by the array subscripts in the following way:

multid_array(row_no,column_no,page_no,book_no,...)

....

bookspages

MATLAB Basics II

ENCMP 100

55©2011 by ECE, UofA

Multidimensional arrays

>>the_3d_array(:,:,1)= [1 3 5; 2 4 6]

>>the_3d_array(:,:,2)=[1 0 0; 0 0 1]

>>the_3d_array(:,:,3)=[10 9 8; 7 6 5]

a 3-dimensional array

rows

columns

pages

Each page should have the same number of rows and columns.

MATLAB Basics II

ENCMP 100

56©2011 by ECE, UofA

Summary … of covered topics

• Basic file input/output commands

save(), load()

• Built-in functions

• The MATLAB arithmetic operators:

scalar, array, and matrix

• Construction of variables.

• Basics of debugging in MATLAB.

• Sub-arrays and multi-dimensional arrays.

MATLAB Basics II

45

Page 46: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

Selection Control Structure

ENCMP

100

2©2011 by ECE, UofA

Overview

• Programming structures

• Relational and logical operators

• Selection statements

• construct if

• construct switch/case

• construct try/catch

• construct menu

• Flowchart and pseudo-code

• Logic function: find

Selection

ENCMP

100

3©2011 by ECE, UofA

Programming Structures - Introduction

The programs we have looked at so far are fairly limited

• they will always perform the same series of instructions, in the same order

• they cannot make decisions about whether or not a particular action(s) needs to be performed

• they can calculate results via expressions, but cannot use those results to effect what they do

We need to see how to add logic and control

structures to our programs to overcome these limitations

Selection

ENCMP

100

4©2011 by ECE, UofA

Programming Structures - Program Flow

The normal flow of program control is sequential.

The sequential flow of control can be altered in precisely defined ways using control structures for• selection

• repetition

• invocation

Any program can be written with just these four control flows nearly every programming language supports these control structures

Selection

46

Page 47: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

5©2011 by ECE, UofA

Programming Structures

• sequence: a list of commands executed one after another, they are executed in

the order in which they are placed within the program

sequence selection repetition

(loop)

invocation

Selection

ENCMP

100

6©2011 by ECE, UofA

Programming Structures

• selection: execution of one set of comments if some criterion is true, or other set if

the criterion is false

sequence selection repetition

(loop)

invocation

Selection

ENCMP

100

7©2011 by ECE, UofA

Programming Structures

• repetition: a group of statements is executed multiple times

sequence selection repetition

(loop)

invocation

Selection

ENCMP

100

8©2011 by ECE, UofA

Programming Structures

• invocation: a group of statements can be invoked (by a call) at any place in the

program – function (we cover it later)

sequence selection repetition

(loop)

invocation

Selection

47

Page 48: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

9©2011 by ECE, UofA

Programming Structures

The selection and repetition structures depend on relational and logical operators.

They are used to determine what commands should be executed

•which path for the case of selection

•should the loop continue for the case of repetition

Selection

ENCMP

100

10©2011 by ECE, UofA

Relational and Logical Operators

Control structures depend on relational and logical operators – they require comparisons (conditions)

• Relational operators make comparisons

• Logical operators allow us to combine the

comparisons

Selection

ENCMP

100

11©2011 by ECE, UofA

Relational Operators

operator interpretation

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== equal to

~= not equal to

Selection

ENCMP

100

12©2011 by ECE, UofA

Relational Operators

the result of comparison is either true orfalse

most computer programs use the number

1 for true and 0 for false

Selection

48

Page 49: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

13©2011 by ECE, UofA

Relational Operators

cash >= 50

condition

operand relational operator

operand

Selection

ENCMP

100

14©2011 by ECE, UofA

Relational Operators

if we define two scalars:x = 5;

y = 1;

and use a relational operator then the result of the comparison is either true or false

for < and x < y the result is 0 (false)

Selection

ENCMP

100

15©2011 by ECE, UofA

Relational Operators (in MATLAB)

if we define two matrices:x = [ 1, 2, 3, 4, 5];

y = [-2, 0, 2, 4, 6];

and use a relational operator <

x < y

the corresponding elements are compared and the result is

0 0 0 0 1

Selection

ENCMP

100

16©2011 by ECE, UofA

Logical Operators

operator interpretation

& and

~ not

| or

Selection

49

Page 50: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

17©2011 by ECE, UofA

Logical Operators – truth tables

Yfalse

true

false

true

~Xtrue

true

false

false

X&Yfalse

false

false

true

X|Yfalse

true

true

true

Xfalse

false

true

true

canOpen = keyTurned & knobTurned canOpen = haveKey1 | haveKey2

Selection

ENCMP

100

18©2011 by ECE, UofA

Relational and Logical Operators

more complex decision situations can be described combining relational and logical operators

(x >= 0) & (x < 100)

compound condition

logical operator

simple condition simple condition

Selection

ENCMP

100

19©2011 by ECE, UofA

Relational and Logical Operators

if we define three matrices:

x = [ 1, 2, 3, 4, 5];

y = [-2, 0, 2, 4, 6];

z = [ 8, 8, 8, 8, 8];

and use the following comparison

z > x & z > y

the result will be

1 1 1 1 1

Selection

ENCMP

100

20©2011 by ECE, UofA

Relational and Logical Operators

for the same three matrices:

x = [ 1, 2, 3, 4, 5];

y = [-2, 0, 2, 4, 6];

z = [ 8, 8, 8, 8, 8];

and the following comparison

x > y | x > z

the result will be

1 1 1 0 0

Selection

50

Page 51: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

21©2011 by ECE, UofA

Precedence of Operations

logical operators are grouped according to precedence (highest to lowest):

NOT ~ right to left associative

AND & left to right associative

OR | left to right associative

NOT’s are grouped first, from right to left in an expression if there are a number of them present

AND’s are next, and are grouped from left to right if there are a number of them present

finally, OR’s are grouped, again from left to right if there are a number of them present in the expression

Selection

ENCMP

100

22©2011 by ECE, UofA

Precedence of Operations

right to left=

| left to right

& left to right

== ~= left to right

< <= > >=

left to right+ -

left to right* / %

right to left~

associativityoperator

left to right

Selection

ENCMP

100

23©2011 by ECE, UofA

The & and | operators

The concept of short-circuit

- second operand is evaluated only when the result is

not fully determined by the first operand

The &, and | operators do not short-circuit, in general,

but they DO if used in with if or while expressions

The operators that do short-circuit are && and ||

(those operators require logical scalars)

Selection

ENCMP

100

24©2011 by ECE, UofA

The & and | operators

>> a = [1 1];

>> b = [2 0 1];

>> a|b

??? Error using ==> or

Inputs must have the same size.

>> if (a|b) disp('okay'), end;

okay

>> if (b|a) disp('okay'), end;

??? Error using ==> or

Inputs must have the same size.

Selection

51

Page 52: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

25©2011 by ECE, UofA

The && and || operators

>> a = 2;

>> b = 0;

>> x = (b ~= 0) && (a/b > 18.5)

x =

0

Selection

ENCMP

100

26©2011 by ECE, UofA

Simple if

if comparison

statements

end

if the comparison (a logical expression) is true, the statements between the if statement and the end

statement are executed

(good practice: to indent the statements inside an if

structure)

Selection

ENCMP

100

27©2011 by ECE, UofA

Simple if

what does an if statement mean if the

comparison includes a matrix?

the comparison is only true if it is true for

every member of the array

Selection

ENCMP

100

28©2011 by ECE, UofA

Example 5.1: simple if

x = 3;

y = 7;

if x<y

disp(‘x is smaller than y’);

end

Selection

52

Page 53: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

29©2011 by ECE, UofA

Example 5.2: simple if

x = 3;

y = 7;

z = 2;

if x>z & x>y

disp(‘x is between z and y’);

end

Selection

ENCMP

100

30©2011 by ECE, UofA

Construct if/else

the simple if triggers the execution of statements if a condition is true

if it is false those statements are skipped, and

the program continues without doing anything

what if instead you want to execute an alternate set of statements if the condition is false?

Selection

ENCMP

100

31©2011 by ECE, UofA

Construct if/else

Statements to execute if the

comparison is true

ComparisonTrue False

Statements to

execute if the comparison is false

Selection

ENCMP

100

32©2011 by ECE, UofA

Construct if/else

if comparison

statements

else

statements

end

Selection

53

Page 54: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

33©2011 by ECE, UofA

Example 5.3: if/else

x = 3;

y = 7;

z = 2;

if x>z & x<y

disp(‘x is between z and y’);

else

disp(‘x is not between z and y’);

end

Selection

ENCMP

100

34©2011 by ECE, UofA

Example 5.4: if/else%weight.m: calculate your weight on other planet

%create variables

clear;clc;

%the acceleration rate due to gravity on earth

g=9.81;

%factors of the acceleration rate on other planets relative to g

f_mars=0.38;

f_jupiter=2.50;

f_pluto=0.04;

%input the weight at the command prompt

w_earth=input('Please input your weight on earth (in kg): ');

%select the planet at the command prompt

planet_id = input('Choose the planet 1-mars,2-jupiter,3-pluto: ');

%display weight on the Earth

disp(['your weight on the Earth is (in kg): ' num2str(w_earth)]);

Selection

ENCMP

100

35©2011 by ECE, UofA

Example 5.4-cont’d%calculate and display weight depending on the planet selection

if planet_id == 1

w = w_earth*f_mars;

disp(['your weight on the Mars is (in kg): ' num2str(w)]);

end

if planet_id == 2

w = w_earth*f_jupiter;

disp(['your weight on the Jupiter is (in kg): ' num2str(w)]);

end

if planet_id == 3

w = w_earth*f_pluto;

disp(['your weight on the Pluto is (in kg): ' num2str(w)]);

end

if planet_id < 1 || planet_id > 3

disp('sorry - provided selection is not valid');

end

Selection

ENCMP

100

36©2011 by ECE, UofA

Construct if/elseif/else

when multiple selection criteria we should use the structure elseif

Selection

54

Page 55: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

37©2011 by ECE, UofA

Construct if/elseif/else

if comparison

statements

elseif comparison

statements

elseif comparison

else

statements

end

Selection

ENCMP

100

38©2011 by ECE, UofA

Example 5.5: if/elseif/else(different version of Example 5.4)…

%calculate and display weight depending on the planet selection

if planet_id == 1

%for mars

w = w_earth*f_mars;

disp(['your weight on the Mars is (in kg): ' num2str(w)]);

elseif planet_id == 2

%for jupiter

w = w_earth*f_jupiter;

disp(['your weight on the Jupiter is (in kg): ' num2str(w)]);

elseif planet_id == 3

%for pluto

w = w_earth*f_pluto;

disp(['your weight on the Pluto is (in kg): ' num2str(w)]);

else

disp('sorry - provided selection is not valid');

end

Selection

ENCMP

100

39©2011 by ECE, UofA

Construct if/else - tips

write the nominal path through the code first,

then write the exceptions

- the normal path through the

code is clear

make sure that you branch correctly on equality

- think what you should use: >, <,

>=, <=

- think twice before using == (especially

in the case of floating point numbers)

Selection

ENCMP

100

40©2011 by ECE, UofA

put the normal case after the if rather than after the else

- put the case you normally expect to process first

follow the if clause with a meaningful statement

if (some_test) if (!some_test)

; …

else

Construct if/else - tips

Selection

55

Page 56: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

41©2011 by ECE, UofA

consider the else clause

- if you have if without else, unless the reason is

obvious, use comments to explain why the else clause is not necessary

test both the if and else clauses

check for reversal of the if and else clauses

put the most common cases first

- you minimize the amount of code someone has to read to find usual cases

- you improve efficiency (code “does” less tests)

Construct if/else - tips

Selection

ENCMP

100

42©2011 by ECE, UofA

Structure: switch/case

this structure is an alternative to the if/elseif/else structure

the code is generally easier to read

this structure allows you to choose between multiple outcomes, based on some criterion, which must be exactly true

Selection

ENCMP

100

43©2011 by ECE, UofA

Structure: switch/case

when to use

the criterion can be either a scalar (a number) or a string

in practice, it is used more with strings than with numbers

Selection

ENCMP

100

44©2011 by ECE, UofA

Structure: switch/case

switch variable

case option1

code executed if variable == option1

case option2

code executed if variable == option2

otherwise

code executed if variable ~= any option

end

Selection

56

Page 57: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

45©2011 by ECE, UofA

Structure: switch/case

IMPORTANT

once a “true” case has been found, the program does not check the other cases

Selection

ENCMP

100

46©2011 by ECE, UofA

Example 5.6: switch/case(different version of Example 5.4)…

%calculate and display weight depending on the planet selection

switch planet_id

case 1

% for mars

w = w_earth*f_mars;

disp(['your weight on the Mars is (in kg): ' num2str(w)])

case 2

%for jupiter

w = w_earth*f_jupiter;

disp(['your weight on the Jupiter is (in kg): ' num2str(w)]);

case 3

%for pluto

w = w_earth*f_pluto;

disp(['your weight on the Pluto is (in kg): ' num2str(w)]);

otherwise

disp('sorry - provided selection is not valid');

end

Selection

ENCMP

100

47©2011 by ECE, UofA

Structure: switch/case

In general, the switch/case construct is:

switch variable

case {option1, option2}

code executed if variable == option1 or option2

case option3

code executed if variable == option3

otherwise

code executed if variable ~= any option

end

Selection

ENCMP

100

48©2011 by ECE, UofA

Example 5.7: switch/case

switch value

case {1, 3, 5, 7, 9}

disp(‘The value is odd’);

case {2, 4, 6, 8, 10}

disp(‘The value is even’);

otherwise

disp(’The value is out of range');

end

Selection

57

Page 58: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

49©2011 by ECE, UofA

Structure: try/catch

It is a special case of branching designed to trap errors.

Ordinarily, when a MATLAB program encounter and error while running – the program aborts.

The try/catch modifies this behavior.

If an error occurs in the try block, then instead of aborting, the code in the catch block is executed, and

the program keeps running.

If there are no errors, the code in the catch block is

skipped.

Selection

ENCMP

100

50©2011 by ECE, UofA

Structure: try/catch

try

statement1

statement2 try block

catch

statement1

statement2 catch block

end

Selection

ENCMP

100

51©2011 by ECE, UofA

Example 5.8: try/catch

% initialize array

a = [1 2 3 4 5];

try

% display element of a given subscript

index = (‘Enter subscript of element: ‘);

disp([‘a (’,num2str(index),’) = ‘, num2str(a(index))]);

catch

% if error occurs (wrong index)

disp([’Wrong index: ’, num2str(index)]);

end

Selection

ENCMP

100

52©2011 by ECE, UofA

Structure: menu

a MATLAB function used in conjunction with a switch/case structure

it causes a menu box to appear on the screen with a series of buttons defined by the programmer

Selection

58

Page 59: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

53©2011 by ECE, UofA

Structure: menu

because the input is controlled by a menu box, the user can’t accidentally enter a bad choice

this means you don’t need the otherwise portion of the switch/case structure

Selection

ENCMP

100

54©2011 by ECE, UofA

Example 5.9: menu(different version of Example 5.4)

%weight.m: calculate your weight on other planet

%create variables

clear;clc;

%the acceleration rate due to gravity on earth

g=9.81;

%factors of the acceleration rate on other planets relative to g

f_mars=0.38;

f_jupiter=2.50;

f_pluto=0.04;

%input the weight at the command prompt

w_earth=input('Please input your weight on earth (in kg): ');

%select the planet at the command prompt

planet_id = menu('Choose the planet', 'mars', 'jupiter', 'pluto');

%display weight on the Earth

disp(['your weight on the Earth is (in kg): ' num2str(w_earth)]);

Selection

ENCMP

100

55©2011 by ECE, UofA

Flow Charts and Pseudo-Code

For more complicated programs – it becomes more and more important to plan your code before you write it

Flow charts – graphical approach

Pseudo-code – verbal description

Selection

ENCMP

100

56©2011 by ECE, UofA

Pseudo-Code: procedure

•Outline a set of statements describing the steps you will take to solve the problem

•Convert these steps into comments

•Insert the appropriate code into the file between the comment lines

Selection

59

Page 60: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

57©2011 by ECE, UofA

Example 5.10: Pseudo-Code (1)

create a program to convert miles/hr to ft/s

the output should be a table, complete with title and column headings

Selection

ENCMP

100

58©2011 by ECE, UofA

Example 5.10: Pseudo-Code (2)

Define a vector of mph values

Convert mph to ft/s

Combine the mph and ft/s vectors into a matrix

Create a table title

Create column headings

Display the table

Selection

ENCMP

100

59©2011 by ECE, UofA

Example 5.10: Pseudo-Code (3)

Convert steps into comments%Define a vector of mph values

%Convert mph to ft/s

%Combine the mph and ft/s vectors into a matrix

%Create a table title

%Create column headings

%Display the table

Selection

ENCMP

100

60©2011 by ECE, UofA

Example 5.10: Pseudo-Code (4)

Add MATLAB code between comments%Define a vector of mph values

mph = 0:10:100;

%Convert mph to ft/s

fps = mph*5280/3600;

%Combine the mph and ft/s vectors into a matrix

table = [mph;fps];

%Create a table title

disp(‘Velocity Conversion Table’);

%Create column headings

disp(‘ mph f/s’);

%Display the table

fprintf(‘%8.0f %8.2f \n’, table);

Selection

60

Page 61: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

61©2011 by ECE, UofA

Flow Charts: concept

•Especially appropriate for more complicated programs

•Create a big picture graphically

•Convert to pseudo-code

Selection

ENCMP

100

62©2011 by ECE, UofA

Flow Charts – basic elements

• an oval indicates the beginning of a section of code

• a parallelogram indicates an input or output

• a diamond indicates a decision point

• calculations are placed in rectangles

Selection

ENCMP

100

63©2011 by ECE, UofA

Flow Charts: example

This flow chart represents the conversion program.

Start

Define a vector

of miles/hour

Calculate the

ft/sec vector

Combine into a

table

Create an output

table using disp

and fprintf

End

Selection

ENCMP

100

64©2011 by ECE, UofA

Flow Charts and Pseudo-Code

Both flow charts and pseudo-code are especially appropriate for complicated programming tasks.

You can create a “big picture” of your program graphically and then convert it to pseudo-code.

Selection

61

Page 62: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

65©2011 by ECE, UofA

Logic Functions

MATLAB offers, so called, logic functions that can perform similar tasks as traditional selection and repetition structures

The primary logical function is: find

Selection

ENCMP

100

66©2011 by ECE, UofA

Logic Functions

find

searches a matrix and identifies which elements in that matrix meet a given criteria

Selection

ENCMP

100

67©2011 by ECE, UofA

Logic Function: find

let’s consider

height = [180, 171, 191, 177, 169];

accept = find(height >= 175)

it returns

accept =

1 3 4

NOTE: find returns the index numbers

Selection

ENCMP

100

68©2011 by ECE, UofA

Logic Function: find

if we want to now the actual heights

height = [180, 171, 191, 177, 169];

accept = find(height >= 175)

height(accept)

ans =

180 191 177

Selection

62

Page 63: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

69©2011 by ECE, UofA

Example 5.11: Search (1)

by combining relational and logical operators you can

create fairly complicated search criteria

example

write a program that selects applicants that are at least 18 years old and less than 35 years old, and are at least 175 cm high

Selection

ENCMP

100

70©2011 by ECE, UofA

Example 5.11: Search (2)

Applicant pool

Height Age

180 18

171 19

191 34

177 20

169 18

180 36

174 22

Selection

ENCMP

100

71©2011 by ECE, UofA

Example 5.11: Search (3)

Pseudo-code

Create a 7x2 matrix of applicant height and age information

Use the find command to determine which applicants are eligible

Use fprintf to create a table of results

Selection

ENCMP

100

72©2011 by ECE, UofA

Example 5.11: Search (4)

Pseudo-code

%Create a 7x2 matrix of applicant height and age information

%Use the find command to determine which applicants are eligible

%Use fprintf to create a table of results

Selection

63

Page 64: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

05_SELECTION

ENCMP

100

73©2011 by ECE, UofA

Example 5.11: Search (5)%Create a 7x2 matrix of applicant height and age

applicants =[180,18;171,19;191,34;177,20;169,18;180,36;174,22]

%Use the find command to determine which applicants are eligible

pass = find(applicants(:,1) >= 175 & applicants(:,2)>=18 &

applicants(:,2)<35)

%Use fprintf to create a table of results

results = [pass, applicants(pass,1), applicants(pass,2)];

fprintf(‘Applicant # %4.0f is %4.0f cm tall and %4.0f years old\n’,

results)

returnsApplicant no. 1 is 180 cm tall and 18 years old

Applicant no. 3 is 191 cm tall and 34 years old

Applicant no. 4 is 177 cm tall and 20 years old

Selection

ENCMP

100

74©2011 by ECE, UofA

Summary … of covered topics

• Program structure

• Operators: relational (<, <=, >, >=, ==, ~=)

• logical (&, |, ~)

• Statements: if if/else if/elseif/else

switch/case try/catch menu

• Flowchart (graphical representation)

• Pseudo-code (verbal description)

• Logic function: find

Selection

64

Page 65: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

Repetition Control Structure

ENCMP

100

2©2011 by ECE, UofA

Overview

• Repetition structures:

• construct for

• construct while

• Statements:

• command break

• command continue

Repetition

ENCMP

100

3©2011 by ECE, UofA

Repetition: for vs. while

Loops are used when you need to repeat a set of

instructions multiple times

for: used when you know how many times you

need to repeat the loop

while: used when you need to keep repeating the

instructions until a criterion is met

Repetition

ENCMP

100

4©2011 by ECE, UofA

Loop for

for index = expr

commands to be executed (body)

end

the first line identifies the loop and defines an index – a number that changes on each pass through the loop; then a group of commands to be executed; finally, the end of loop is identified

Repetition

65

Page 66: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

5©2011 by ECE, UofA

Example 6.1: simple for loop

a simple program to print numbers

for i=1:2:5

disp(['the value of i is: ', num2str(i)]);

end

it returns the value of i is: 1

the value of i is: 3

the value of i is: 5

Repetition

ENCMP

100

6©2011 by ECE, UofA

Loop for: more about expr

expr is the loop control expression, whose result is an array

columns in the array produced by expr are stored one at a time in the variable index, and then the body is executed – the loop is executed once for each column in the array produced by expr

Repetition

ENCMP

100

7©2011 by ECE, UofA

Example 6.2

for k = 1:3

a = k^2

end

a =

1

a =

4

a =

9

Repetition

ENCMP

100

8©2011 by ECE, UofA

Example 6.3

for k = 1:2:6

a = 2^k

end

a =

1

a =

8

a =

32

Repetition

66

Page 67: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

9©2011 by ECE, UofA

Example 6.4

for k = [1 3 7]

k

end

k =

1

k =

3

k =

7

Repetition

ENCMP

100

10©2011 by ECE, UofA

Example 6.5

for k = [1 3 7; 4 5 9]

k

end

k =

[1; 4]

k =

[3; 5]

k =

[7; 9]

Repetition

ENCMP

100

11©2011 by ECE, UofA

Example 6.6: for with matrix as expr

a simple program to sum some numbers

first_sum = 0;

second_sum = 0;

for k = [1 2 3; 10 20 33]

first_sum = first_sum + k(1);

second_sum = second_sum + k(2);

end

disp(['first sum is: ', num2str(first_sum)]);

disp(['second sum is: ', num2str(second_sum)]);

it returns first sum is: 6

second sum is: 63

Repetition

ENCMP

100

12©2011 by ECE, UofA

Loop for: execution

1. MATLAB generates an array by evaluating the control expression

2. the first time – the program assigns the 1st column of the array to index, and executes the statements within

the body

3. after execution of all statements, the next column is assigned to index, and execution is repeated

4. the step 3 is repeated, as long as there are additional columns in the array

Repetition

67

Page 68: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

13©2011 by ECE, UofA

Example 6.7 problem description

Write a program to calculate the power measurements in decibels (dB) according to the following formula

assume P1=1W, while P2 is changing from 1W to 20W, in 0.5W steps. Plot the dB-versus-power curve on a log-

linear scale.

dB =10log10

P2

P1

Repetition

ENCMP

100

14©2011 by ECE, UofA

Example 6.7solution (1)

Steps:

1.Understand what should be done:

calculate the values of power measurements for given values of P2 – from 1W to 20W with a step of 0.5, and plot the results

2.Define the inputs and outputs

input – P2 changes in a given way

output – semi log plot of results

3.Design the algorithm

Repetition

ENCMP

100

15©2011 by ECE, UofA

Example 6.7solution (2)

3. Design the algorithm

- to calculate power measurements in dB from 1W to 20W (step 0.5W)

- create an array to hold calculated decibels

- calculate the decibels for a provided P2

- plot the decibel values in semilog plot

4. Write a program

5. Test a program

Repetition

ENCMP

100

16©2011 by ECE, UofA

Example 6.7 program

% to calculate power measurements in dB

% from 1W to 20W (step 0.5W)

clear; clc;

% create an array to hold calculated decibels

dB_values = zeros(1,39);

% calculate the decibels for a provided P2

for step=0:38

P2 = 1+0.5*step;

dB_values(step+1)=10*log10(P2);

End

% plot the decibel values in semilog plot

semilogy(dB_values);

Repetition

68

Page 69: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

17©2011 by ECE, UofA

Vectorization

Very often it is possible to perform calculation with either for loops or vectors.

Both approaches produce the same results, but for loop

is slower.

Repetition

ENCMP

100

18©2011 by ECE, UofA

Example 6.8:(vectorization of example 6.7)

% to calculate power measurements in dB

% from 1W to 20W (step 0.5W)

clear; clc;

% create an array of P2s

P2=1:0.5:20;

% calculate the decibels for provided P2s

dB_values=10*log10(P2);

% plot the decibel values in semilog plot

semilogy(dB_values);

Repetition

ENCMP

100

19©2011 by ECE, UofA

Loop while

while expression

commands to be executed (body)

end

expression produces a logical value; if expression is true the code block will be executed, and after that

control will return to the while statement; this process will be repeated until the expression becomes false – the

program will execute the first statement after end

Repetition

ENCMP

100

20©2011 by ECE, UofA

Example 6.9: simple while loop

a simple program to print numbers

i = 1;

while i <= 5

disp(['the value of i is: ', num2str(i)]);

i = i + 2;

end

it returnsthe value of i is: 1

the value of i is: 3

the value of i is: 5

Repetition

69

Page 70: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

21©2011 by ECE, UofA

Example 6.10: while loop application

one common use for a while loop is error checking of

user input

for example, if we ask user to enter a positive number, and we can use while loop to confirm that the number

is not a negative one – if it is negative, we prompt for a positive one

Repetition

ENCMP

100

22©2011 by ECE, UofA

Example 6.10: while loop application

% to calculate a log10(x) value

clear; clc;

% to ask user for a value

x = input(‘Enter a positive value: ’);

% to check if x is positive, if not – keep asking

while (x <= 0)

disp(‘You entered a negative number!’);

x = input(‘Enter a positive value: ’);

end

% to calculate log10(x)

y= log10(x);

Repetition

ENCMP

100

23©2011 by ECE, UofA

Loop while: how to build one

Step 1

identify the one test that must be true when the loop is finished

Step 2

use the opposite (negative) form of the test identified in Step 1 as

the loop expression

Step 3

within the body of the while loop, do the minimal amount of work

to progress towards the completion of the loop, ensuring that

the expression will eventually become false

Step 4

do whatever is required before or after the loop to ensure that the

goal is reached

Repetition

ENCMP

100

24©2011 by ECE, UofA

Example 6.11problem description

Calculate factorials N!

N! = 1*2*3*4* … *N

Repetition

70

Page 71: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

25©2011 by ECE, UofA

Example 6.11solution (1)

Steps:

1.Understand what should be done:

calculate N!

2.Define the inputs and outputs

input – N

output – value of N!

3.Design the algorithm

Repetition

ENCMP

100

26©2011 by ECE, UofA

Example 6.11solution (2)

start

ask for N

Init: counter, factorial

while N<counter

counter = counter + 1

factorial = factorial * counter

display factorial

stop

N

Y

Repetition

ENCMP

100

27©2011 by ECE, UofA

Example 6.11program

% to calculate factorial of N

clear; clc;

N = input(‘Enter a positive integer: ’);

% initialize the factorial

factorial = 1;

% initialize the counter

counter = 1;

% calculate the value of factorial for N

while counter<N

counter = counter + 1;

factorial = factorial*counter;

end

disp(['the factorial of ', num2str(N), ' is ', num2str(factorial)]);

Repetition

ENCMP

100

28©2011 by ECE, UofA

Example 6.12improvement of previous example

When you ask for N – check if N is positive:

ask for N

display: you entered negative number

while N<0

ask for N

Init: counter, factorial

Repetition

71

Page 72: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

29©2011 by ECE, UofA

Example 6.12program% to calculate factorial of N

clear; clc;

N = input(‘Enter a positive integer: ’);

while (N < 0)

disp(‘You entered a negative number!’);

N = input(‘Enter a positive integer: ’);

end

% initialize the factorial

factorial = 1;

% initialize the counter

counter = 1;

% calculate the value of factorial for N

while counter<N

counter = counter + 1;

factorial = factorial*counter;

end

disp(['the factorial of ', num2str(N), ' is ', num2str(factorial)]);

Repetition

ENCMP

100

30©2011 by ECE, UofA

Command break

break command can be used to terminate a loop

prematurely (while the comparison in the first line is still true)

it will cause termination of the smallest enclosing whileor for loop

Repetition

ENCMP

100

31©2011 by ECE, UofA

Example 6.13: command break

n=0;

while(n<10)

n=n+1;

a=input(‘Enter a value > 0: ’);

if(a<=0)

disp(‘you must enter positive number’)

disp(‘the program will terminate’)

break

end

disp(‘the natural log of that number is’)

disp(log(a))

end

Repetition

ENCMP

100

32©2011 by ECE, UofA

Command break

in the program, the entered number is checked, and if it is

zero or negative, an error message is sent to the command window and the program jumps out of loop

if the value of a is positive, the program continues until n

is finally greater than 10

Repetition

72

Page 73: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

33©2011 by ECE, UofA

Command continue

continue command is similar to break, however

instead of terminating the loop, the program just skips to

the next pass

Repetition

ENCMP

100

34©2011 by ECE, UofA

Example 6.14: command continue

n=0;

while(n<10)

n=n+1;

a=input(‘Enter a value > 0: ’);

if(a<=0)

disp(‘you must enter positive number’)

disp(‘try again’)

continue

end

disp(‘the natural log of that number is’)

disp(log(a))

end

Repetition

ENCMP

100

35©2011 by ECE, UofA

Command continue

in the program, if you enter a negative number, the program lets you try again – until the value of n is finally greater than 10

Repetition

ENCMP

100

36©2011 by ECE, UofA

Nested loops

it is possible for one loop to be completely inside another

loop

if for loops are nested – they should have independent

loop index variables

if a break or continue statement is used inside a set

of nested loops – that statement refers to the innermost of the loops

Repetition

73

Page 74: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

06_REPETITION

ENCMP

100

37©2011 by ECE, UofA

Example 6.15: nested loops

for ii = 2: 3

for jj = 1: 2

product = ii*jj;

fprintf(‘%d * %d = %d\n’, ii, jj, product);

end

end

returns2 * 1 = 2

2 * 2 = 4

3 * 1 = 3

3 * 2 = 6

Repetition

ENCMP

100

38©2011 by ECE, UofA

Comparison: for versus while

for index = 1: 2: 10

disp([‘value is: ‘, num2str(index)]);

end

index = 1;

while index <=10

disp([‘value is: ‘, num2str(index)]);

index = index + 2;

end

Repetition

ENCMP

100

39©2011 by ECE, UofA

Summary … of covered topics

• loops: for

• loops: while

• commands: break and continue

Repetition

74

Page 75: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

Overview

• Inputs into a program

• Displaying results generated by a program• revisiting disp, input, load, num2str, and save

commands• learning format, fprintf, sprintf, and fopen

commands

2

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem to be solved

We will compute how long you need to own a car to make it economically advantageous to purchase a hybrid car vs. a car with a standard engine.

Model MSRP Overall fuel economy

2010 Toyota Camry Sedan Hybrid $26,150 34 mpg = 6.92 L/100km

2010 Toyota Camry Sedan $20,445 26 mpg = 9.05 L/100km

2010 Ford Fusion Sedan Hybrid $27,950 39 mpg = 6.03 L/100km

2010 Ford Fusion Sedan $19,695 24 mpg = 9.80 L/100km

We assume cost to own = purchase cost + gasoline cost

We will prompt the user for the estimated cost of a liter of gasoline and his/her mileage per year.

We will show and plot the cost to own as a function of the years/months when the car is owned, and we will also find the break-even point where costs to own of the standard and hybrid vehicles are equal.

Most importantly, we will neatly format the outputs.

3

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

Formatting of inputs and outputs

MATLAB provides a few built-in functions for importing the inputs and formatting of the outputs

• Input functions include input and load

• Functions for formatting outputs include disp, format, fprintf, sprintf, and save

Some of these functions, such as input, load, save, and disp, were introduced before. Today we will discuss them and the other functions in more detail.

4

75

Page 76: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The inputs

The input data could be hard-coded (specified in your code) or acquired from a user or a file

• input command prompts the user to enter data,

it accepts different data types including scalars, matrices and character strings

• load command allows to load data from a fileload filename -ascii

filename is a name of the file which you want to load

- by default MATLAB assumes .mat extension of the file (and that this file is in MAT-file format), unless the filename specifies the extension.

- if the extension is not .mat then MATLAB assumes that the data is in ASCII format. You can use -ascii to specify that the file is in ASCII

format.

5

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The inputs

ASCII and MAT-file formats• MAT-file format is specific to MATLAB and it includes

name and type of each variable, size of each array, and all data values

this format should be used when your data is used inside the MATLAB environment. That includes MATLAB on different computers and different platforms (PC, Mac, Unix, etc.)

• ASCII format assumes that the values are ASCII character strings that are comma- or space-separated

this format should be used when you want to exchange the data between MATLAB and other applications

MATLAB will load the data from such file into a variable that has the same name as the filename (without the extension)

6

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The inputs

Example ASCII file (file created in slide 19 using –ascii option)

6.9200000e+000

9.0500000e+0006.0300000e+000

9.8000000e+000

2.6150000e+004

2.0445000e+004

2.7950000e+0042.7950000e+004

7

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The inputs

Example MAT-file (file created in slide 19)

MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Thu Aug 26 12:04:32 2010 ? ı IM ı ???3???xœãc``ð?b6 æ€Ò À

å3"aN NK ı ONÌ-ªÌ€ªã„ª[çþ°Jd ı ı́ ? ı = °ı ???-???xœãc``p?b6 æ€Ò À

å3"a ı ?-5>91·¨’ı ÊŸ5 ı ı $ ı ?sÝ K ı ???/???xœãc``p?b6 æ€Ò À

å3"a ı ?-5>-¿(%ƒ ı Ê—o}ı ¸CN ı ?pı ×ı ???-???xœãc``p?b6 æ€Ò À

å3"av NK ı OË/Jaà„ÊÏš ı Ê ı ?mô Z ı ???2???xœãc``p?b6 æ€Ò À

å3"an ö

ı

ˆONÌ-ªÌ?«ca`bPKc`??lÒ ı 5 ı ???1???xœãc``p?b6 æ€Ò À

å3"a. ö

ı

ˆONÌ-ª„¨ca`b¸ëÏÀ??iı ı lı ???1???xœãc``p?b6 æ€Ò Àå3"a. ö

ı

ˆOË/JÉ€¨ca`bÐËe`??fæ ı Ò

8

76

Page 77: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

Handling specialized files

MATLAB also includes I/O functions for specialized file formats (such as xls or jpg)

• these functions can be found if you type doc fileformats in the command window

For example, wavwrite and wavread can be used for wav files and xlswrite and xlsread can be used for Excel files

MATLAB includes support for text (delimited text files), spreadsheet (XLS from MS Excel), XML (eXtensible Markup Language), image (BMP, GIF, JPEG, PCX, PNG, TIFF, ICO and few other formats), audio (WAV and SND), and video (AVI, MJ2, MPG, ASF, ASX, and WMV formats) files.

9

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs

disp(variable)

variable could be a variable name or a character string.disp shows the contents of a given variable without printing its name.

Removing semicolon in a given line in your M-file shows the values of the variable from that line including the name.

Use the num2str(x) function to change numeric data to a string when using disp to show a string and a numeric value together.

fuel_economy = 6.92;

disp(['Fuel economy of 2010 Camry Sedan Hybrid in L/100km is '

num2str(fuel_economy)]);

returnsFuel economy of 2010 Camry Sedan Hybrid in L/100km is 6.92

10

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs

format format_type

The value that we format is 12.345678901234567

11

ENCMP 100

©2011 by ECE, UofA

fprintf(format_string, variables)

• A formatted output print function, it writes data in a user specified format to a file or to the command window. Hereby we introduce some of the basic options for this function. We will utilize and explore it later in the course.

• It uses the same formatting specifications as in the computer language C.

• A general fprintf function looks like this:fprintf(format_string, variables)

a string containing special formatting information for the value in var1

the array containing values to be displayed

The outputs

12 Formatting of Inputs/Outputs

77

Page 78: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofA

fprintf(format_string, variables)

days = 60;

fprintf(‘There are %f days left in this term’, days)

The above returns:

There are 60.000000 days left in this term>>

The first argument is a string containing the characters to be displayed and the formatting characters (also referred to as the type field), which controls how the array (e.g. days) is displayed. %f indicates that the array days will be displaced as a floating point number.

The second argument contains an array or a list of arrays (separated by comma) to be displayed.

The outputs

13 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

fprintf(format_string, variables)

The type field contains the sign %, indicating where the array is inserted in the string, also called a place holder and is immediately followed by the conversion characters, e.g.

%f fixed-point notation %e exponential notation%d decimal notation%g whichever is shorter, %f or %e%c characters shown on at the time%s string of characters

The outputs

14 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

fprintf(format_string, variables)

One can also specify the length of variables by using the optional width field and precision field.width field: a positive integer specifying the minimum number of digits to be printedprecision field: preceded by a period (.) and specifies the number of decimal places after the decimal point.

dist = 2.5;

fprintf(‘The distance is %5.2f miles \n’, dist)

returnsThe distance is 2.50 miles

there are two spaces before 2 because the no. of characters to be shown is 5, with 2 reserved for the part after the decimal point

The outputs

15 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs

fprintf(format_string,variables)

fuel_economy = 6.92;

model = '2010 Camry Sedan Hybrid';

fprintf('Fuel economy of the %s is %4.2f L/100km\n', model,

fuel_economy);

returns

Fuel economy of the 2010 Camry Sedan Hybrid is 6.92 L/100km

16

78

Page 79: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofA

fprintf(format_string,variables)

MATLAB does not automatically start a new line after fprintffunction is executed. That’s why you see the command prompt >> at the end of each line in the previous slides.

With two or more separated fprintf functions, the results show on the same line. A linefeed \n is needed at the end of the format string to start a new line. Other escape characters that format how the line is displaced and located are:

\r: carriage return (similar to linefeed \n)\t: tab\b: backspace

The outputs

17 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

fprintf(format_string,variables)

When the variable to print in fprintf is a two dimensional matrix, MATLAB uses the values in one column at a time from the first column to the last.

Use fprintf() function to display a matrix in a table format.%feet to inches conversion

feet = 1:4;

inches = feet.* 12;

conv_table=[feet; inches];

fprintf(‘%4.0f %7.2f \n’, table);

returns1 12.00

2 24.00

3 36.00

4 48.00

The outputs

18 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs directly to a file

file_id = fopen(filename,permission)

This function opens a file either to read it contents or to save to it• load and specialized read functions are faster and more

convenient to read from files

• writing directly to a file allows to combine text and numericaldata

• fprintf function is used to format data to be written into a file

file_id is an identifier (nickname) of the text file. The file_id is a positive integer if file is successfully opened,

and -1 if the open fails.filename is a string specifying the name of the file to openpermissions is a string specifying mode in which the file is

opened

19

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs directly to a file

file_id = fopen(filename,permission)

permissions strings'r' open existing file for reading only (default) ('r+' for reading and writing)'w' delete contents of existing file (or create new) and open for writing only

(‘w+' for writing and reading)

'a' open existing file (or create new) for writing only appending to the end of the file ('a+' for writing and reading)

'rt' ('wt' and 'at') specify that the file is opened in text mode

'rb' ('wb' and 'ab') specify that the file is opened in binary mode (default)

status = fclose(file_id)

status equals 0 if file is successfully closed, and -1 if the close fails

This allows other programs to gain access to the file.

20

79

Page 80: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs directly to a file

fprintf(file_id,format_string,variables)

Allows to send formatted output to a text file.

file_id = fopen('car_economy_study.txt','wt');

% wt defines that we write to the file in text mode

fuel_economy = 6.92;

model = '2010 Camry Sedan Hybrid';

fprintf(file_id,'Fuel economy of the %s is %4.2f

L/100km\n',model,fuel_economy)

fclose(file_id);

returns the number of bytes saved in the file:ans =

60.00

21

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs

variable = sprintf(format_string,variables)

Similar to fprintf, except that it assigns the resulting string into the variable.

This variable can be used in other places of your program, e.g.,to specify the contents of a text box in a graph.

fuel_economy = 6.92;

model = '2010 Camry Sedan Hybrid';

label = sprintf('Fuel economy of %s is %4.2f L/100km\n',

model,fuel_economy);

22

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs

save filename variables_to_save -ascii

filename is a name of the file where data will be saved

By default MATLAB assumes .mat extension and MAT-file format, unless the filename specifies the extension and you use -ascii to specify that the file should be in the ASCII format

variables_to_save is a space separated list of variables to be saved.

The entire workspace is saved if you will not provide the variable names.

23

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The outputs

save filename variables_to_save -ascii

Note that the only things being saved are the values stored in the workspace window. You will not be saving the commands from the command window (you can use diary command for that).

Save the MAT-files using the .mat extension and use other extensions (such as .dat or .txt) for the ASCII-formatted files.

save is faster than using fprintf to write to a file but it cannot handle saving of custom formatted text and numerical data.

24

80

Page 81: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofA

The issue with load/save

The function load works when the file is “regular” – the same type of data on every line, and in the same format on every line.However, if this is not the case – load can not be used.

Similarly, the save function can write matrices to a file, but if the output is not a simple matrix – problem.

A solution: lower level functions to read from/write to a file.

25 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

Opening a file: additional information

The function fopen returns:

-1 if the opening is not successfulinteger number if it is successful, this number

becomes file identifier

After the fopen is attempted the value returned should be tested to make sure the the file was successfully opened.

26 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

Example 7.1: opening a file

% opening a file

fid = fopen(‘sample.txt’);

if fid == -1

disp(‘File open not successful’);

else

% read the file content

end

close_result = fclose(fid);

if close_result == 0

disp(‘File close successful’);

else

disp(‘File close not successful’);

end

27 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

Reading from a file

Lower level I/O functions:• fscanf – reads formatted data into a matrix, using

conversion formats such as %d for integers, %s for strings, and %f for floats (doubles)

• textscan – reads text data from a file and stores it in a cell array

• fgetl and fgets – functions read strings from a file one line at at time

28 Formatting of Inputs/Outputs

81

Page 82: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofA

Reading from a file: fgetl & fgets

fgetl and fgets

• these functions read strings from a file one line at at time, the difference is that the fgets keeps the newline character if there is one at the end of the line, whereas the fgetl function gets rid of it

• since both of them read one line at a time, these functions are typically in some form of a loop

• these functions afford more control over how data is read

29

Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

Reading from a file: end of file

The functions fgetl and fgets read only one line at at time, they are placed in a loop.

This loop keeps going until the end of file is reached.

The function feof(fid)returns logical true if the end of file fid has been reached, or logical false if not.

30 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

Reading from a file: an algorithm

A general algorithm for reading from a file into a string:

1.open the file; check if the opening was successful2.if opened, loop until the end of file; for each line:

• read the line into a string• manipulate the data

3.close the file; check if closing was successful

31 Formatting of Inputs/Outputs

ENCMP 100

©2011 by ECE, UofA

Example 7.2: reading from a file% opening a file

fid = fopen(‘sample.txt’);

if fid == -1

disp(‘File open not successful’);

else

% read the file content

while feof(fid) == 0 % or while ~feof(fid)

aline = fgetl(fid);

% use string functions to extract numbers

end

close_result = fclose(fid);

if close_result == 0

disp(‘File close successful’);

else

disp(‘File close not successful’);

end

end

32 Formatting of Inputs/Outputs

82

Page 83: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem

Create the input data fileModel MSRP Overall fuel economy2010 Toyota Camry Sedan Hybrid $26,150 34 mpg = 6.92 L/100km

2010 Toyota Camry Sedan $20,445 26 mpg = 9.05 L/100km2010 Ford Fusion Sedan Hybrid $27,950 39 mpg = 6.03 L/100km2010 Ford Fusion Sedan $19,695 24 mpg = 9.80 L/100km

fe_camryh = 6.92;

fe_camry = 9.05;

fe_fordh = 6.03;

fe_ford = 9.8;

MSRP_camryh = 26150;

MSRP_camry = 20445;

MSRP_fordh = 27950;

MSRP_ford = 19695;

save car_economy_study_inputs.mat fe_camryh fe_camry fe_fordh

fe_ford MSRP_camryh MSRP_camry MSRP_fordh MSRP_fordh;

33

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem

Develop the solution for the Toyota Camry% program file car_economy_study.m

% Purpose: comparison of cost of hybrid and standard cars

% Author: Lukasz Kurgan

clear, clc

% load input data from file

load car_economy_study_inputs.mat;

% request input from user

fuel_cost = input('Estimated cost of 1 liter of gasoline? ');

mileage = input('How many kilometers per year do you make? ');

% establish mileage scale in km per month

mileage_scale = 0:mileage/12:mileage*25;

% calculate the cost to own

cost_h = MSRP_camryh + mileage_scale.*(fe_camryh/100)*fuel_cost;

cost_s = MSRP_camry + mileage_scale.*(fe_camry/100) *fuel_cost;

continued on the next slide

34

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem

Develop the solution for the Toyota Camry% calculate the break-even point

break_even_point = -1;

for i=1:length(mileage_scale)

if (cost_h(i) < cost_s(i))

break_even_point = i;

break;

end

end

% save the results into a txt file

file_id = fopen('car_economy_study.txt','wt');

fprintf(file_id,'Yearly cost to own the Toyota Camry assuming fuel

at $%4.2f/L and %6.0f km/year\n',fuel_cost,mileage);

continued on the next slide

35

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem

Develop the solution for the Toyota Camry

fprintf(file_id,'Years owned Cost of hybrid Cost of standard\n');

for i=1:12:length(mileage_scale)

fprintf(file_id,'\t%2.0f \t\t\t %8.2f \t\t %8.2f \n',i/12,

cost_h(i),cost_s(i));

end

if (break_even_point ~= -1)

fprintf(file_id,'The hybrid model will be more economical

after %2.0f months',break_even_point);

else

fprintf(file_id,'The hybrid model will be more expensive

over the first 25 years');

end

fclose(file_id);

continued on the next slide

36

83

Page 84: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

07_FORMATTING I/O

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem

Develop the solution for the Toyota Camry

% plot the results

plot(1:length(cost_h),cost_h, 1:length(cost_s),cost_s)

title('Cost to own the Toyota Camry')

xlabel('Months owned')

ylabel('Cost to own')

grid

legend('Cost of hybrid model','Cost of standard model')

if (break_even_point ~= -1)

break_even_text = sprintf('Hybrid model is more economical

after %2.0f months',break_even_point);

else

break_even_text = sprintf('Hybrid model will be more expensive

over the first 25 years');

end

text(100,MSRP_camryh,break_even_text)

37

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

The problem

Our solution is hard-coded for the Toyota Camry while a user may want to consider other cars

• in the next class we will learn how to develop M-files that would allow for a more generic solution

38

ENCMP 100

©2011 by ECE, UofAFormatting of Inputs/Outputs

Summary … of covered topics

• Input functions input and load• Output functions disp, format, fprintf, sprintf,

and save

• The input function allows the user to interact with the program by entering data at a prompt

• The disp function displays information in the command window

• fprintf function is more versatile than the disp function and allows to combine text and numerical data in a formatted output and to save to a text file

• sprintf is similar to fprintf and it allows to save formatted output to a variable name, for later use in your program

39

84

Page 85: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

User-defined Functions

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Overview

• How to create and use MATLAB functions with both single and multiple inputs and outputs

• How variables are passed into functions

• How to declare and use global variables

• How to create and use subfunctions

2

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Why functions?

When working on a program to solve a given problem we often use so called top-down design

• We start with a statement of a problem and a list of inputs and outputs

• Next, we describe an outline of the problem and divide it into sub-problems (sub-tasks)

some of the sub-tasks may be further subdivided

• Next, each sub-tasks is implemented and tested separately

• Finally, the codes that implement these sub-tasks are merged and tested together

• In prior lectures we combined the code into a single large program, which did not allow to code, correct and test smaller sub-tasks independently

3

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Scripts vs. Functions

The M-files that we created so far have been scripts• Collections of MATLAB statements stored in a file

• When executed, the result is the same as if these statements would be directly typed in the Command Window

• Scripts use the Command Window workspace

variables in the workspace created before executing the script are available to this script and variables declared in the script remain in the workspace after the script is executed

• Scripts have no input arguments and they do not return results

they “communicate” with other scripts through variables left in the workspace

4

85

Page 86: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Scripts vs. Functions

MATLAB functions are special M-files that have their own workspace

• They do not have direct access to variables in the Command Window workspace

they cannot change their values (which could happen by accident)

• They execute faster that the scripts

• They receive input data through input argument list

• They return results through output argument list

they “communicate” with the Command Window workspace and other functions through the output arguments, which are stored in the Command Window workspace

5

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions: benefits (1)

MATLAB allows to package individual sub-tasks into separate functions, which provides certain benefits

• Independent testing of sub-tasks

You can test each sub-task separately before combining them into large

program when testing becomes more complex. This step is called unit testing.

• Reusable code

If the same sub-tasks need to be executed multiple times (in multiple

places) in your main program then you can reuse the same function, instead of copying code. In some cases sub-tasks (functions) can be reused in multiple programs.

6

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions: benefits (2)

MATLAB allows to package individual sub-tasks into separate functions, which provides certain benefits

• Isolation from unintended side-effects

Each functions has its own workspace with its own variables. This is

very important as it prevents accidental mistakes within a function from affecting the contents of the Command Window workspace

for instance, your function could use the same variable names asthe variables in the Command Window workspace and you could unintentionally overwrite their values

• Easier maintenance of programs

After being released, functions are often maintained (improved,

modified, fixed) by programmers who did not write the original version. They have limited knowledge of the overall program and could introduce “side-effect” that would have wide-spread effects if functions would not provide isolation.

7

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions

function [outarg1,outarg2,…]=fname(inarg1,inarg2,…)

% H1 comment line

% other comment line

(executable code)

(return) or (end)

function – is a reserved keyword

fname – specifies the name of the function

inarg – the list of input arguments

outarg – the list of function return values

Functions should be stored in files with the same name (including capitalization) as the function name and with the .m extension.

8

86

Page 87: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions

function [outarg1,outarg2,…]=fname(inarg1,inarg2,…)

% H1 comment line

% other comment line

(executable code)

(return) or (end)

inarg and outarg are called dummy arguments since these are

only placeholders for actual values that are passed from and returned to the caller.

Function can be called (invoked) using actual arguments in the Command Window, in a script, and in another function

9

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions

function [outarg1,outarg2,…]=fname(inarg1,inarg2,…)

% H1 comment line

% other comment line

(executable code)

(return) or (end)

Execution of the function is top-down and ends when either returnstatement, end statement, or when end of the file is reached.

Each outarg must appear on the left side of at least one

assignment statement in the function. When the function returns, the values stored in the output argument list are returned to the caller.

10

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions

function [outarg1,outarg2,…]=fname(inarg1,inarg2,…)

% H1 comment line

% other comment line

(executable code)

(return) or (end)

H1 comment line is a 1-line summary of the purpose of the function (this line is searched and displayed when using lookfor

command).

The subsequent comment lines (until first blank line or executable statement) are displayed by the help command. They should briefly

explain how to use the function.

11

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Example 8.1: simple function

areacirc.m

function [area ,circum ]= areacirc(rad)

% this function calculates the area and circ of a circle

area = pi * rad .* rad;

circum = 2 * pi * rad;

>> [a c] = areacirc(4)

a =

50.3655

c =

25.1327

12

87

Page 88: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Example 8.1: cont’d

>> disp(areacirc(4)) %only the first value is retained

50.3655

help areacirc

>> this function calculates the area and circ of a circle

>> [a c] = areacirc(1:4)

a =

3.1416 12.5664 28.2743 50.3655

c =

6.2832 12.5664 18.8496 25.1327

13

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Pass-by-value

MATLAB programs communicate with their functions using pass-by-value scheme.

• When a function is called, MATLAB make a copy of the actual input arguments and then passed them to the function.

• This means that if the function modifies these arguments, it will not affect the data available to the caller.

• Recall that each function has its own workspace, which means that is also cannot change other variables that are in the workspace of the caller.

• The above prevents unintended side-effects, in which an error in the function might unintentionally modify variables in the calling program.

14

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Example: pass-by-value (1)

Using the following script to call function modify_ab

a = 2; b = [1 4]; c = 4;

fprintf('before calling modify_ab a = %.1f, b = %.1f %.1f\n',a,b);

modify_ab(a, b);

fprintf('after calling modify_ab a = %f, b = %f %f\n',a,b);

function [] = modify_ab(a,b)

fprintf('inside modify_ab a = %f, b = %f %f\n',a,b);

a = a+b;

b = a+b;

fprintf('inside modify_ab a = %f %f, b = %f %f\n',a,b);

>> pass_by_value_example

before calling modify_ab a = 2.0, b = 1.0 4.0

inside modify_ab a = 2.0, b = 1.0 4.0

inside modify_ab a = 3.0 6.0, b = 4.0 10.0

after calling modify_ab a = 2.0, b = 1.0 4.0

15

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Example: pass-by-value (2)

Using the debugging mode to show the workspace

16

88

Page 89: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Global variables

The variables we declared so far are local. They are available only in the Workspace of the function where they are declared.

MATLAB allows declaring global variables that are shared between all Workspaces using global memory

• Keyword global is used to declare these variables.

• Any function can read and change their values.

• Be cautious when declaring and using these variables since they may lead to the side-effects.

• A common practice is to make the names of global variable UPPERCASE and to declare them before the first executable statement (right after the header comments).

• They are useful when sharing large-size variables since they are not copied each time that a function is called.

17

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Example: global variables

Using a modified modify_ab function

18

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Functions with no input/output arguments

MATLAB allows to specify functions with no input and/or no output arguments The modify_ab function that has no output arguments.

function [] = modify_ab(a,b)

fprintf('inside modify_ab a = %f, b = %f %f\n',a,b);

a = a+b;

b = a+b;

fprintf('inside modify_ab a = %f %f, b = %f %f\n',a,b);

Example function that has no input and no output arguments.

function [] = car_economy_study()

This is the “main” (primary) function that will be used to implement solution to our hybrid vs. standard car price problem

19

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Determining number of input and output arguments

MATLAB provides build-in functions to find the number of input/output arguments nargin and nargout functions

>> nargin('modify_ab')

ans =

2.00

>> nargout('modify_ab')

ans =

0

>> nargin('surf')

ans =

-1.00

-1 is returned when functions allows for variable (different) number of input or output arguments

20

89

Page 90: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Function functions

Function whose input arguments include names of other functions; build-in examples include

• fminbnd minimizes a function of one variable

• fzero finds a zero of a function of one variable

• quad numerically integrates a function

• fplot plots a function in given limits on x- and y-axis

• ezplot is an “easy” function plotter that uses default limits

fzero('-0.05*x^2+sin(x)+1',-pi,2*pi)

ans =

-2.32

fminbnd('-0.05*x^2+sin(x)+1',-pi,2*pi)

ans =

5.27

fplot('-0.05*x^2+sin(x)+1',[-pi 2*pi])

21-3 -2 -1 0 1 2 3 4 5 6

-1.5

-1

-0.5

0

0.5

1

1.5

2

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Function functions• fplot plots a function in given limits on x- and y-axis

• ezplot is an “easy” function plotter that uses default limits

fplot('sin',[0 2*pi -2 2])

hold

fplot('-0.05*x^2+1',[0 2*pi -2 2])

ezplot('sin')

hold

ezplot('-0.05*x^2+1')

22 -6 -4 -2 0 2 4 6

-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

x

-0.05 x2+1

0 1 2 3 4 5 6-2

-1.5

-1

-0.5

0

0.5

1

1.5

2

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Subfunctions

MATLAB allows to place multiple functions in one M-file

•The top function is called primary function and the functions below are subfunctions

the primary function should have the same name as the file

the subfunctions are accessible only to the other functions in the same file

the subfunctions are used to modularize your code and to make the primary function easier to read

We will declare a subfunction when implementing calculate function

for our hybrid vs. standard car price problem (which is coming next)

23

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Example: the cost to own

We will compute how long you need to own a car to make it economically advantageous to purchase a hybrid car vs. a car with a standard engine.

Model MSRP Overall fuel economy

2010 Toyota Camry Sedan Hybrid $26,150 34 mpg = 6.92 L/100km

2010 Toyota Camry Sedan $20,445 26 mpg = 9.05 L/100km

2010 Ford Fusion Sedan Hybrid $27,950 39 mpg = 6.03 L/100km

2010 Ford Fusion Sedan $19,695 24 mpg = 9.80 L/100km

2010 Honda Civic Sedan Hybrid $23,800 42 mpg = 5.60 L/100km

2010 Honda Civic Sedan $16,455 29 mpg = 8.11 L/100km

2010 GMC Yukon Hybrid $51,185 22 mpg = 10.69 L/100km

2010 GMC Yukon $38,020 17 mpg = 13.84 L/100km

24

90

Page 91: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: data

This data is saved using the following script

models = {'Toyota Camry Sedan' 'Ford Fusion Sedan' 'Honda Civic

Sedan' 'GMC Yukon'};

MSRP = [20445 19695 16455 38020];

MSRP_h = [26150 27950 23800 51185];

fuel_econ = [9.05 9.80 8.11 13.84];

fuel_econ_h = [6.92 6.03 5.60 10.69];

save car_economy_study_inputs.mat models MSRP MSRP_h fuel_econ

fuel_econ_h;

25

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: analysisProblem statementUsing information about MSRP, fuel economy and price, and estimated yearly mileage, the program shall generate plots of the cost to own the hybrid and the standard cars as functions of the years/months when the car is owned, and it shall find the break-even point where the costs to own the standard and hybrid vehicles are equal.

Inputs: MSRP, fuel economy and price, and estimated yearly mileage

Outputs: Break-even point value, plot of the cost to own, and formatted

results saved to a text file.

OutlineStep 1. Load the MSRP and fuel economy from input file

Step 2. Prompt user for fuel price, yearly mileage, and model of the car

Step 3. Calculate cost to own & break-even point for inputs from 1 and 2

Step 4. Save formatted results into a text file (append to previous results)

Step 5. Plot the results

Step 6. Prompt the user to continue; if yes go to step 2, else terminate

26

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: sub-tasks

These steps are potentially repeated multiple times when executing the program. They have well defined inputs and outputs.

collect_user_inputs (STEP 2)

Inputs: available models of the cars

Outputs: fuel price, yearly mileage, and model of the car

calculate (STEP 3)

Inputs: MSRP, fuel economy, fuel price, yearly mileage, and model

Outputs: cost to own, break-even point

save_and_plot (STEPS 4 and 5)

Inputs: fuel price, yearly mileage, cost to own, break-even point, and model

Outputs: text file with the formatted results, formatted plot of the results

27

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

collect_user_inputs functionfunction [fuel_cost,mileage,model] = collect_user_inputs(avail_models)

% collect_user_inputs prompts user for car model, fuel cost and mileage

% The function collects and returns inputs from the user including

% the desired model, the cost of 1 liter of gasoline and yearly mileage.

%

% collect_user_inputs(avail_models)

% avail_models -- an array of strings with the available models

% display and select the available models

model = -1;

while (model < 1 || model > length(avail_models))

fprintf('\nModel number: model name\n');

for i=1:length(avail_models)

fprintf('%2.0f: %s\n',i,avail_models{i});

end

model = input('Select the desired model number: ');

end

model = round(model);

% request other inputs from user

fuel_cost = input('Estimated cost of 1 liter of gasoline? ');

mileage = input('How many kilometers per year do you make? ');

28

91

Page 92: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

collect_user_inputs function

function [fuel_cost,mileage,model] = collect_user_inputs

(avail_models)

• one input argument avail_models which is the cell array with

the available car models

• three output arguments that return the user specified fuel cost,mileage and user-selected car model

• the while loop and round function are used to make sure that

the user selects one of the available models

29

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Accessing the M-file code

MATLAB includes two types of functions

• built-in functions which are not accessible to review

• toolbox functions (either from MATLAB toolboxes or created by the user) which can be accessed using type command

type collect_user_inputs

returnsfunction [fuel_cost,mileage,model] = collect_user_inputs(avail_models)

%collect_user_inputs prompts user for car model, fuel cost and mileage

% The function collects and returns inputs from the user including

% the desired model, the cost of 1 liter of gasoline and yearly mileage.

%

% collect_user_inputs(avail_models)

% avail_models – an array of strings with the available models

% display and select the available models

model = -1;

while (model < 1 || model > length(avail_models))

fprintf('\nModel number: model name\n');

for i=1:length(avail_models)

fprintf('%2.0f: %s\n',i,avail_models{i});

end

model = input('Select the desired model number: ');

end

model = round(model);

% request other inputs from user

fuel_cost = input('Estimated cost of 1 liter of gasoline? ');

mileage = input('How many kilometers per year do you make? ');30

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own - list of functions

car_economy_study (STEPS 1 and 6)

The main function that controls the flow of our program and calls other

functions

collect_user_inputs (STEP 2)

Inputs: available models of the cars

Outputs: fuel price, yearly mileage, and model of the car

calculate (STEP 3)

Inputs: MSRP, fuel economy, fuel price, yearly mileage, and model

Outputs: cost to own, break-even point

save_and_plot (STEPS 4 and 5)

Inputs: fuel price, yearly mileage, cost to own, break-even point, and model

Outputs: text file with the formatted results, formatted plot of the results

31

Step 1. Load the MSRP and fuel economy from input fileStep 2. Prompt user for fuel price, yearly mileage, and model of the carStep 3. Calculate cost to own & break-even point for inputs from 1 and 2Step 4. Save formatted results into a text file (append to previous results)Step 5. Plot the resultsStep 6. Prompt the user to continue; if yes go to step 2, else terminate

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: code (1)function [] = car_economy_study()

% car_economy_study compares costs of standard and hybrid vehicles

% This function uses user-specified costs of 1 liter of gasoline

% and yearly milage to compare costs to own of standard and

% hybrid vehicles for a user-chosen model. The function provides

% text report in the car_economy_study.txt file and visualizes the

% results using a plot.

clear, clc

% load input data from file

load car_economy_study_inputs.mat;

test_end = 1;

while (test_end == 1)

% use collect_user_inputs function to prompt user for inputs

[fuel_cost,mileage,selected_model] = collect_user_inputs(models);

% calculate the cost to own and break-even point

[cost,cost_h,break_even_point] = calculate(MSRP,MSRP_h,fuel_econ,

fuel_econ_h,fuel_cost,mileage,selected_model);

% save and plot the cost and break-even point values

save_and_plot(fuel_cost,mileage,cost,cost_h,break_even_point,

models{selected_model});

% prompt user to continue

test_end = input('\nType 1 to start over and 0 to terminate: ');

end32

92

Page 93: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: code (2)function [fuel_cost,mileage,model] = collect_user_inputs(avail_models)

% collect_user_inputs prompts user for car model, fuel cost and mileage

% The function collects and returns inputs from the user including

% the desired model, the cost of 1 liter of gasoline and yearly mileage.

%

% collect_user_inputs(avail_models)

% avail_models -- an array of strings with the available models

% display and select the available models

model = -1;

while (model < 1 || model > length(avail_models))

fprintf('\nModel number: model name\n');

for i=1:length(avail_models)

fprintf('%2.0f: %s\n',i,avail_models{i});

end

model = input('Select the desired model number: ');

end

model = round(model);

% request other inputs from user

fuel_cost = input('Estimated cost of 1 liter of gasoline? ');

mileage = input('How many kilometers per year do you make? ');

33

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: code (3)function [cost,cost_h,break_even_point] = calculate(MSRP,MSRP_h,

fuel_econ,fuel_econ_h,fuel_cost,mileage,model)

% calculate computes the cost to own and break-even point values

% The function uses the MSRP, fuel economy, cost of 1 liter of gas

% and yearly milage to calculate cost to own of regular and hybrid

% vehicles of the same model and to compute the break-even point where

% their costs are equal.

%

% calculate(MSRP,MSRP_h,fuel_econ,fuel_econ_h,fuel_cost,mileage,model)

% MSRP -- manufacturer suggested retail price of the standard cars

% MSRP_h -- manufacturer suggested retail price of the hybrid cars

% fuel_econ -- fuel_economy of the standard cars

% fuel_econ_h -- fuel_economy of the hybrid cars

% fuel_cost -- cost of 1 liter of gasoline

% mileage -- number of km to be driven per year

% model -- number of the user-chosen car model

% establish mileage scale in km per month

mileage_scale = 0:mileage/12:mileage*25;

% calculate the monthly cost to own using subfunction

calculate_monthly_cost

cost = calculate_monthly_cost(MSRP,model,mileage_scale,fuel_econ,

fuel_cost);

cost_h = calculate_monthly_cost(MSRP_h,model,mileage_scale,fuel_econ_h,

fuel_cost);

continued on the next slide34

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: code (4)% calculate the break-even point

break_even_point = -1;

for i=1:length(mileage_scale)

if (cost_h(i) < cost(i))

break_even_point = i;

break;

end

end

% subfunction that calculates the monthly cost to own

function monthly_cost = calculate_monthly_cost(MSRP,model,mileage_scale,

fuel_econ,fuel_cost)

monthly_cost = MSRP(model) +

mileage_scale.*(fuel_econ(model)/100) *fuel_cost;

35

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: code (5)function [] = save_and_plot(fuel_cost,mileage,cost,cost_h,

break_even_point,model_name)

% save_and_plot plots the results and saves them in text file

% This function visualizes and stores the cost to own and

% break-even point values. A text report is saved in the

% car_economy_study.txt file and the results are shown using 2D plot

%

% save_and_plot(cost,cost_h,break_even_point,model)

% cost -- the calculated (per month) cost of the standard cars

% costh -- the calculated (per month) cost of the hybrid cars

% break_even_point -- month when costs of standard and hybrid are equal

% model_name -- name of the user-chosen car model

% save the results into a txt file

file_id = fopen('car_economy_study.txt','at');

fprintf(file_id,'Yearly cost to own %s assuming fuel at $%4.2f/L and

%6.0f km/year\n',model_name,fuel_cost,mileage);

fprintf(file_id,'Years owned Cost of hybrid Cost of standard\n');

for i=1:12:length(cost)

fprintf(file_id,'\t%2.0f \t\t\t %8.2f \t\t %8.2f \n',i/12,cost_h(i),

cost(i));

end

continued on the next slide

36

93

Page 94: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: code (6)if (break_even_point ~= -1)

fprintf(file_id,'The hybrid model will be more economical after %2.0f

months\n\n',break_even_point);

else

fprintf(file_id,'The hybrid model will be more expensive over the

first 25 years\n\n');

end

fclose(file_id);

% plot the results

plot(1:length(cost_h),cost_h, 1:length(cost),cost)

title_text = sprintf('Cost to own the %s',model_name);

title(title_text), xlabel('Months owned'), ylabel('Cost to own')

grid

legend('Cost of hybrid model','Cost of standard model')

if (break_even_point ~= -1)

break_even_text = sprintf('Hybrid model is more economical after %2.0f

months',break_even_point);

else

break_even_text = sprintf('Hybrid model will be more expensive over

the first 25 years');

end

text(100,cost_h(1),break_even_text)37

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own problem

38

Step 1. Load the MSRP and fuel economy from input fileStep 2. Prompt user for fuel price, yearly mileage, and model of the carStep 3. Calculate cost to own & break-even point for inputs from 1 and 2Step 4. Save formatted results into a text file (append to previous results)Step 5. Plot the resultsStep 6. Prompt the user to continue; if yes go to step 2, else terminate

0 50 100 150 200 250 300 3501.5

2

2.5

3

3.5

4

4.5

5

5.5

6x 10

4 Cost to own the Ford Fusion Sedan

Months owned

Cost

to o

wn

Hybrid model is more economical after 168 months

Cost of hybrid model

Cost of standard model

0 50 100 150 200 250 300 3503

4

5

6

7

8

9

10x 10

4 Cost to own the GMC Yukon

Months owned

Cost

to o

wn

Hybrid model will be more expensive over the first 25 years

Cost of hybrid model

Cost of standard model

Next two slides show the contents of the text file

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: output (1)Yearly cost to own Ford Fusion Sedan assuming fuel at $1.05/L and 15000 km/year

Years owned Cost of hybrid Cost of standard

0 27950.00 19695.00

1 28899.72 21238.50

2 29849.45 22782.00

3 30799.17 24325.50

4 31748.90 25869.00

5 32698.63 27412.50

6 33648.35 28956.00

7 34598.07 30499.50

8 35547.80 32043.00

9 36497.53 33586.50

10 37447.25 35130.00

11 38396.97 36673.50

12 39346.70 38217.00

13 40296.43 39760.50

14 41246.15 41304.00

15 42195.88 42847.50

16 43145.60 44391.00

17 44095.32 45934.50

18 45045.05 47478.00

19 45994.78 49021.50

20 46944.50 50565.00

21 47894.23 52108.50

22 48843.95 53652.00

23 49793.68 55195.50

24 50743.40 56739.00

25 51693.13 58282.50

The hybrid model will be more economical after 168 months

39

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

The cost to own: output (2)Yearly cost to own GMC Yukon assuming fuel at $1.05/L and 15000 km/year

Years owned Cost of hybrid Cost of standard

0 51185.00 38020.00

1 52868.68 40199.80

2 54552.35 42379.60

3 56236.03 44559.40

4 57919.70 46739.20

5 59603.38 48919.00

6 61287.05 51098.80

7 62970.72 53278.60

8 64654.40 55458.40

9 66338.07 57638.20

10 68021.75 59818.00

11 69705.43 61997.80

12 71389.10 64177.60

13 73072.77 66357.40

14 74756.45 68537.20

15 76440.13 70717.00

16 78123.80 72896.80

17 79807.48 75076.60

18 81491.15 77256.40

19 83174.82 79436.20

20 84858.50 81616.00

21 86542.18 83795.80

22 88225.85 85975.60

23 89909.52 88155.40

24 91593.20 90335.20

25 93276.88 92515.00

The hybrid model will be more expensive over the first 25 years

40

94

Page 95: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

08_FUNCTIONS

ENCMP 100

©2011 by ECE, UofAUser-defined Functions

Summary … of covered topics

• Differences between scripts and functions

• Why functions are useful

• Defining functions

• Pass-by-value scheme and global variables

• Function functions

• Subfunctions

41

95

Page 96: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

String Functions

ENCMP

100

2©2011 by ECE, UofAStrings and String Functions

Overview

• character codes: ASCII

• type char() in MATLAB

• 1D and 2D arrays

• removing white spaces from strings

• string functions: concatenate, compare, replace, find matching …

• “checking” string characters

• type conversion functions

ENCMP

100

3©2011 by ECE, UofA

Introduction to Strings in MATLAB

• Computer programs are frequently required to handle text (e.g., screen output to human users, keyboard input from human users, human-readable stored data).

• MATLAB (like most programming languages) provides special functions to simplify the handling of strings.

• In a 64-bit PC, integers and floating-point numbers are represented using 64 bits (8 bytes) each.

• Characters are represented in MATLAB using 16 bits (2 bytes) each. A string is an array of characters.

• str = 'This is a dummy string';

• Variable str is an array of char's, of dimension 1x22,

that occupies 44 bytes of memory.

Strings and String Functions

ENCMP

100

4©2011 by ECE, UofA

Character Encodings

• Character codes are required to represent all of the required symbols in a human-readable language.

• In English, we need codes for at least the following:

• 26 upper case letters, 26 lower case letters, space character

• 10 decimal digits

• punctuation marks (e.g., !, ?, ', ", ;, :, etc.)

• common symbols (e.g., #, $, %, &, *, +, =, <, >, /, \, @, etc.)

• Other codes are useful to have for text formatting, and to control input/output devices.

• linefeed, carriage return, end-of-transmission, ring the bell, etc.

• Other languages use Roman letters with accents, or use entirely different character sets, or use ideograms.

Strings and String Functions

96

Page 97: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

5©2011 by ECE, UofA

The 7-bit ASCII Code for Characters

"American Standard Code for Information Exchange

0123456789

0110000011000101100100110011011010001101010110110011011101110000111001

ABCDEF..

YZ

100000110000101000011100010010001011000110

.

.

10110011011010

abcdef..

yz

110000111000101100011110010011001011100110

.

.

11110011111010

In addition to the 10 digit codes and 52 letter codes:• space character + 32 printable symbols• delete code + 32 other nonprintable control codes

Strings and String Functions

ENCMP

100

6©2011 by ECE, UofA

The Full ASCII Code in Tabular Form

Source: www.wikipedia.org

Strings and String Functions

ENCMP

100

7©2011 by ECE, UofA

International Character Encodings

• ASCII was designed in 1963 to be efficient at repre-senting English and for controlling (now mostly obsolete features) on input/output equipment of that time.

• ASCII appeared at a critical moment in the Computer Revolution, when there was a need to standardize printers, terminals, etc., so it became very widely used.

• ASCII was also a useful tool for competitors of the then dominant IBM Corp. (which used its own EBCIDIC character code). ASCII helped to create a high-volume market for standard non-IBM input/output devices.

• Recently ASCII is being replaced by multilingual codes, such as the Unicode standard. MATLAB uses 16-bit character codes that will allow it to support Unicode.

Strings and String Functions

ENCMP

100

8©2011 by ECE, UofA

Testing for the presence of "char"s

• Character constants (of type char) and strings (1-D arrays of char) are created by enclosing characters in single quotation marks.

• The ischar() function can be used to test for the presence of a scalar char or an array of char’s.

>> var1 = 'd';

>> var2 = '124';

>> var3 = 124;

>> ischar(var1)

ans =

1 % one char

>> ischar(var2)

ans =

1 % a string (array of chars)

>> ischar(var3)

ans =

0 % one integer

Strings and String Functions

97

Page 98: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

9©2011 by ECE, UofA

Convertion: "char"s vs. "doubles"s

The functions char() and double() can be used to convert between the char and double data types:

>> str = 'This is a test'

str =

This is a test

>>

>> x = double(str) % string -> array-of-doubles

x =

84 104 105 115 32 105 115 32 97 32 116 101 115 116

>>

>> z = char(x) % array-of-doubles -> string

z =

This is a test

Strings and String Functions

ENCMP

100

10©2011 by ECE, UofA

1-D and 2-D Character Arrays

• A string is a 1-dimensional array of "char"s:

EmployeeName = 'Stephen J. Chapman'; % 1x18

• Sometimes it is useful to create 2-dimensional arrays of char’s. Careful: Each row of a 2-D array must have the

same length, or else you get a MATLAB error.

• Illegal: char2d = ['red’;'white’;'blue'];

• O.K.: char2d = ['red ‘;'white’;'blue '];

• The char() built-in function will automatically insert the

necessary padding (using space characters):

• char2d = char('red','white','blue');

• This creates a legal 3x5 array of char’s.

Strings and String Functions

ENCMP

100

11©2011 by ECE, UofA

Removing Trailing Whitespace

Function deblank() removes all of the blank characters from the end of a string.

>> array_2D = char('Long string 1','String 2')

array_2D =

Long string 1

String 2 % 5 trailing blanks

>>

>> size(array_2D(2,:))

ans =

1 13

>>

>> deblanked_row = deblank(array_2D(2,:));

>> size(deblanked_row)

ans =

1 8

Strings and String Functions

ENCMP

100

12©2011 by ECE, UofA

Concatenating (Joining) Strings

• Function strcat() can be used to join two (or more)

strings together. Any trailing blanks are deleted.>> new_string = strcat('String 1 ','String 2 ')

new_string =

String 1String 2 % 1x16 character array

• Function strvcat() allows strings to be joined vertically to make legal 2-D arrays of char’s. Padding

(blank characters) is added automatically to equalize the lengths of the rows.>> result = strvcat('Long String 1 ','String 2')

result = % 2x14 character array

Long String 1

String 2

Strings and String Functions

98

Page 99: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

13©2011 by ECE, UofA

Concatenating (Joining) Strings

• When the function strcat() is used any trailing blanks

are deleted. If you need to avoid this, another approach to concatenation should be applied – you can use square brackets.

• Let’s compare the use of strcat() and square bracket

concatenation with strings that contain trailing spaces:

>> a = 'hello ';

>> b = 'goodbye';

>> c = strcat(a, b)

c =

hellogoodbye

>> d = [a, b]

d =

hello goodbye

Strings and String Functions

ENCMP

100

14©2011 by ECE, UofA

Comparing Individual Characters (1)

Testing two char’s for equality (==) or nonequality (~=) is

done in the same way for all character encodings.

>> 'a' == 'a' % Note: equality has two = signs

ans =

1

>> 'a' == 'A'

ans =

0

>> 'a' ~= 'z'

ans =

1

>> 'Z' ~= 'Z'

ans =

0

Strings and String Functions

ENCMP

100

15©2011 by ECE, UofA

Comparing Individual Characters (2)

Other relational operators (>, >=, <, <=) can be used to

compare the values of the corresponding ASCII codes.

>> 'a' < 'b'

ans =

1

>> 'B' > 'C'

ans =

0

>> '&' <= '&'

ans =

1

>> 'S' >= 'T'

ans =

0

Strings and String Functions

ENCMP

100

16©2011 by ECE, UofA

Comparing Strings Using Operators

• The relational operators (>, >=, <, <=, ==, ~=) can be

used to compare all of the characters in two arrays of characters.

• The arrays must have equal dimensions.

>> 'abc' == 'abc'

ans =

1 1 1

>> 'aBc' ~= 'ABc'

ans =

1 0 0

>> '716' <= '666'

ans =

0 1 1

Strings and String Functions

99

Page 100: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

17©2011 by ECE, UofA

Comparing Strings: strcmp()

>> strcmp('abc','abc')

ans =

1

>> strcmp('abc','aBc')

ans =

0

>> strcmpi('abc','aBc')

ans =

1

The function strcmp() determines whether two strings

are both (1) equal in length, and (2) contain the same characters. The function strcmpi() does the same, but

it ignores the case of letters.

Strings and String Functions

ENCMP

100

18©2011 by ECE, UofA

Comparing String Prefixes: strncmp()

The function strncmp() determines whether two strings

contain the same "n" leading characters, where "n" is the third parameter. The function strncmpi() does the

same, but it ignores the case of letters.

>> strncmp('abcst','abdefqr',2)

ans =

1

>> strncmp('abcst','abdefqr',3)

ans =

0

>> strncmpi('AbcSt','aBcSwQ',3)

ans =

1

Strings and String Functions

ENCMP

100

19©2011 by ECE, UofA

Characterizing Characters within Strings

• The functions isletter() and isspace() get the

positions of letters and spaces, respectively, in a given string. But they may be removed from MATLAB.

• Always use the new function isstrprop(), which can

test for all of the following character properties:'alpha' Is the char alphabetic (is it a letter)?

'alphanum' Is the char alphanumeric (is it a letter or a digit)?

'cntrl' Is the char a control character?

'digit' Is the char a numerical digit?

'lower' Is the char a lower case letter?

'wspace' Is the char a "white space" char (e.g., space, newline,

carriage return, tab, vertical tab, formfeed)?

'upper' Is the char an upper case letter?

'xdigit' Is the char a hexadecimal digit (e.g., 0-9, a-f, A-F)

Strings and String Functions

ENCMP

100

20©2011 by ECE, UofA

Examples: isstrprop()

>> isstrprop('67f %E3','alpha')

ans =

0 0 1 0 0 1 0

>> isstrprop('67f %E3','digit')

ans =

1 1 0 0 0 0 1

>> isstrprop('67f %E3','alphanum')

ans =

1 1 1 0 0 1 1

>> isstrprop('67f %E3','wspace')

ans =

0 0 0 1 0 0 0

Strings and String Functions

100

Page 101: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

21©2011 by ECE, UofA

Finding a substring within a string

The function findstr() finds the starting position of all

occurrences of a short string within a longer string.

>> findstr('Get thee there','the')

ans =

5 10

>> findstr('a b a d a a z',' a ')

ans =

4 8 10

>> findstr('Mississippi','is')

ans =

2 5

Strings and String Functions

ENCMP

100

22©2011 by ECE, UofA

Finding Matching Rows in an Array

The function strmatch() finds the rows in an array that

match the given substring.

>> array_2D = strvcat('maxarray','min val','max val')

array_2D =

maxarray

min val

max val

>> result = strmatch('max',array_2D)

result =

1

3

Strings and String Functions

ENCMP

100

23©2011 by ECE, UofA

Search for a Substring and Replace

The function strrep() finds and then replaces all

occurrences of a first substring in a given string with copies of a second substring.

>> string = 'This is my greatest test!'

string =

This is my greatest test!

>> result = strrep(string,'test','pest')

result =

This is my greapest pest!

Strings and String Functions

ENCMP

100

24©2011 by ECE, UofA

Removing the First Token from a String

The function strtok() collects and removes a "token"

string from the leading characters in a second string up until a "token delimiter" (by default a space).

[token,remainder] = strtok('This is a mess!')

token =

This % prefix up until before 1st blank

remainder =

is a mess! % delimiter blank still there

[token,remainder] = strtok('This is a mess!','m')

token =

This is a % prefix up until before first m

remainder =

mess! % delimiter char m still there

Strings and String Functions

101

Page 102: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

25©2011 by ECE, UofA

Upper and Lower Case Conversion

• The function upper() modifies a string by converting all

lower case letters to upper case:>> result = upper('This is Test 12!')

result =

THIS IS TEST 12!

• The function lower() modifies a string by converting

all upper case letters to lower case:>> result = lower('This is Test 12!')

result =

this is test 12!

Strings and String Functions

ENCMP

100

26©2011 by ECE, UofA

Removing Leading and Trailing Whitespace

The function strtrim() removes all leading and trailing

whitespace characters from a string:

>> test_str = ' This is a test. '

test_str =

This is a test.

>> length(test_str)

ans =

21

>> test_str1 = deblank(test_str)

test_str1 =

This is a test. % 18 chars long

>> test_str2 = strtrim(test_str)

test_str2 =

This is a test. % 15 chars long

Strings and String Functions

ENCMP

100

27©2011 by ECE, UofA

Numeric-to-string Function int2str()

The function int2str() converts a numerical value (of type double) into the corresponding string.

>> value = 2538

value =

2538 % integer value

>> str_val = int2str(value)

str_val =

2538 % string value

>> whos

Name Size Bytes Class Attributes

value 1x1 8 double

strVal 1x4 8 char

Strings and String Functions

ENCMP

100

28©2011 by ECE, UofA

Numeric-to-string Function num2str()

• The function num2str() converts a numerical value (of

any numeric type) into the corresponding string.

• An optional second parameter controls formatting.

>> p = num2str(pi)

p =

3.1416 % string value

>> p = num2str(pi,7)

p =

3.141593 % double value

>> p = num2str(pi,'%10.5e')

p =

3.14159e+000 % string value

Strings and String Functions

102

Page 103: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

29©2011 by ECE, UofA

String-to-Numeric Conversion Functions

• Function str2double() converts a string into the corresponding numerical value of type double.

• Function sscanf() converts a string into a number according to a format control string.

>> a = '3.141592'; % string value

>> b = str2double(a)

b =

3.1416 % double value

>> float_val = sscanf(a,'%g')

float_val =

3.1416 % double value

>> dec_val = sscanf(a,'%d')

dec_val =

3 % integer value

Strings and String Functions

ENCMP

100

30©2011 by ECE, UofA

Formatted Output into a String

• Function sprintf() is similar to the formatted output function fprintf() except that the output is sent into

a string instead of the Command Window.

• This function is useful for creating programmable titles and labels for plots.

>> str = sprintf('The value of pi = %8.6f.',pi)

str =

The value of pi = 3.141593.

>> str = sprintf('The value of pi = %6.4f.',pi)

str =

The value of pi = 3.1416.

Strings and String Functions

ENCMP

100

31©2011 by ECE, UofA

Converting an Array into a String

Function mat2str() joins together all of the elements

of an array, row-by-row, to form one string.

>> a = [1 2 3; 4 5 6]

a =

1 2 3

4 5 6

>>

>> b = mat2str(a)

b =

[1 2 3; 4 5 6]

Strings and String Functions

ENCMP

100

32©2011 by ECE, UofA

Evaluating MATLAB code: eval()

• The function eval() evaluates (i.e., interprets or

executes) a string containing a MATLAB expression.

• The string (containing a MATLAB program) can be created and executed by a MATLAB program.

>> a = '2 * 3.14159';

>> b = eval(a)

b =

6.2832

>> whos

Name Size Bytes Class Attributes

a 1x12 24 char

b 1x1 8 double

Strings and String Functions

103

Page 104: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

09_STRING FUNCTIONS

ENCMP

100

33©2011 by ECE, UofAStrings and String Functions

Summary … of covered topics

• ASCII: more information

• 1D and 2D arrays

• removing white spaces from strings:

• multiple string functions:

ischar(), deblank(), strcat(), strvcat(),

strcmp(), strncmp(), isletter(), isspace(),

isstrprop(), findstr(), strmatch(), strrep(),

strtok(), upper(), lower(), strtrim(),

int2str(), num2str(), str2double(), mat2str(),

eval()

104

Page 105: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

Cell arrays, Structures, and Structure Arrays

ENCMP 100

©2011 by ECE, UofACell arrays and structures

Overview

• New data structures:• cell arrays

• structures

• structure arrays

• How these structures are created and how they can be visualized and modified

• cell, celldisp, and cellplot functions for cell

arrays

• struct, rmfield, and fieldnames functions for

structures and structure arrays

2

ENCMP 100

©2011 by ECE, UofA

Arrays, cell arrays, structures, and structure arrays

Cell arrays, structures and structure arrays are convenient to group related variables togethere.g., in our case study about fuel consumption instead of storing information about model, MSRP, and fuel economy of different cars in three separate variables, they could be grouped together using a cell array called cars.

In contrast to the regular arrays, they allow to group different types of variablesmodel is a string, while fuel economy is a double

3Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Arrays: definition

Array is a data type in which individual elements are of the same type (e.g., only doubles, characters).

It has one name for the whole data structure;

single values are stored in elements identified by numbers (locations in the array).

>> MSRP = [20445 19695; 26150 27950]

MSRP =

20445 19695

26150 27950

>> MSRP(1,1)

ans =

20445

>> fuel_econ = [9.05 9.80; 6.92 6.03];

4Cell arrays and structures

105

Page 106: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Cell arrays: definition

Cell array is a data structure that stores values of different types (e.g., strings and doubles).

It has one name for the whole data structure in which individual elements could be of different types;

Each element is identified by its number (location in the cell array)

5Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: how to create

Cell array are created in a similar way as arrays, but curly braces are used instead of square brackets.

for example: let’s create a cell array in which one element stores integer, one element stores a character, one element stores an 1D array, and one element stores a string

>> cell_row = {113, '%', [2, 3, 4], 'hello world'}

cell_row =

[113] '%' [1x3 double] 'hello world'

6Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: how to create (cont.)

… a column cell array

>> cell_column = {113; '%’; [2, 3, 4]; 'hello world'}

cell_column =

[ 113]

'%'

[1x3 double]

'hello world'

7Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: how to create (cont.)

… a 2x2 cell array

>> cell_matrix = {113, '%’; [2, 3, 4], 'hello world'}

cell_matrix =

[ 113] '%'

[1x3 double] 'hello world'

8Cell arrays and structures

106

Page 107: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Cell arrays: how to create (cont.)

another method: create empty cell and assign values to specific elements, or start assigning values

>> cell_example01 = cell(2,2)

cell_example01 =

[] []

[] []

>> cell_example02{2,2} = 12

cell_example03 =

[] []

[] [12]

9Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: accessing elements …

Similar as in the case of array, but we use curly braces:

>> cell_row{4}

ans =

hello world

>> cell_vector{2}

ans =

%

10Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: accessing elements (cont.)

>> cell_matrix(2,1)

ans =

[1x3 double]

>> cell_matrix{2,1}

ans =

2 3 4

>> cell_matrix{2,1}(2)

ans =

3

11Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: accessing elements (cont.)

>> cell_row{2:3}

ans =

%

ans =

2 3 4

>> cell_example01{1,1}= 123

cell_example01 =

[123] []

[] []

12Cell arrays and structures

Page 108: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

107

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Cell arrays: more realistic example

In the fuel consumption case study instead of having three different arrays: one for models, one for MSRP, and one for fuel efficiency we could have:

1x3 cell array using assignment

>> cars = {{'Toyota Camry Sedan' 'Ford Fusion Sedan'; 'Toyota Camry

Sedan hybrid' 'Ford Fusion Sedan hybrid'}, [20445 19695; 26150

27950], [9.05 9.80; 6.92 6.03]};

>> cars

cars =

{2x2 cell} [2x2 double] [2x2 double]

13Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: example (cont.)

3x1 cell array using assignment>> cars = {{'Toyota Camry Sedan' 'Ford Fusion Sedan'; 'Toyota Camry

Sedan hybrid' 'Ford Fusion Sedan hybrid'}; [20445 19695; 26150

27950]; [9.05 9.80; 6.92 6.03]};

cars =

{2x2 cell }

[2x2 double]

[2x2 double]

2x2 cell array using assignmentcars = {{'Toyota Camry Sedan' 'Ford Fusion Sedan'; 'Toyota Camry

Sedan hybrid' 'Ford Fusion Sedan hybrid'}, []; [20445 19695; 26150

27950], [9.05 9.80; 6.92 6.03]};

14Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: example (cont.)

>> cars

cars =

{2x2 cell } []

[2x2 double] [2x2 double]

15

cell 1,1

'Toyota Camry Sedan' 'Ford Fusion Sedan' 'Toyota Camry Sedan hybrid' 'Ford Fusion Sedan …

cell 1,2

[]

cell 2,1

20445 1969526150 27950

cell 2,2

9.0500 9.80006.9200 6.0300

Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: example – another method

The cell function allows to pre-allocate empty cell array

of the specified size and does that more efficiently (faster) than when using the assignment:

- cell(2,2) tells MATLAB to immediately allocate the

2x2 array

- cars{1,1}= … declares 1x1 cell array; when we add a new element with cars{2,1} command, MATLAB

creates a new array large enough to include this new element, copies the “old” 1x1 array into the “new” 2x1 array, populates the data in the {2,1} cell, and then deletes the “old” array

16Cell arrays and structures

108

Page 109: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Cell arrays: example – cell function

>> cars = cell(2,2)

cars =

[] []

[] []

>> cars{1,1} = {'Toyota Camry Sedan' 'Ford Fusion Sedan';

'Toyota Camry Sedan hybrid' 'Ford Fusion Sedan hybrid'};

>> cars{2,1} = [20445 19695; 26150 27950];

>> cars{2,2} = [9.05 9.80; 6.92 6.03];

>> cars

cars =

{2x2 cell } []

[2x2 double] [2x2 double]

17Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: example – assignment

>> cars{1,1} = {'Toyota Camry Sedan' 'Ford Fusion Sedan';

'Toyota Camry Sedan hybrid' 'Ford Fusion Sedan hybrid'};

>> cars{2,1} = [20445 19695; 26150 27950];

>> cars{2,2} = [9.05 9.80; 6.92 6.03];

>> cars

cars =

{2x2 cell } []

[2x2 double] [2x2 double]

>> cars{2,1}

ans =

20445 19695

26150 27950

18Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: example – viewing contents

Using round brackets shows the data structure of a given element>> cars(2,1)

ans =

[2x2 double]

Using curly brackets shows the data in the element >> cars{2,1}

ans =

20445 19695

26150 27950

Using second set of round brackets shows a particular subset of data in the element>> cars{2,2}(1,1)

ans =

9.0500

19Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: viewing contents

Using celldisp function to show the full contents of the

cell array>> celldisp(cars)

cars{1,1}{1,1} =

Toyota Camry Sedan

cars{1,1}{2,1} =

Toyota Camry Sedan hybrid

cars{1,1}{1,2} =

Ford Fusion Sedan

cars{1,1}{2,2} =

Ford Fusion Sedan hybrid

cars{2,1} =

20445 19695

26150 27950

cars{1,2} =

[]

cars{2,2} =

9.0500 9.8000

6.9200 6.0300

20

The model is actually also

a cell arrays with strings

Cell arrays and structures

109

Page 110: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Cell arrays: viewing contents

Using cellplot function to visualize the cell array

>> cellplot(cars);

21Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: extending

The cell array can be extended by assigning a new element outside of the current size

>> cars{3,3} = [2009, 2010; 2009, 2010];

>> cellplot(cars);

• this will result in creation of a new larger cell array and copying of the “old”array into the “new” one

22Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: modifying

Individual elements can be changed

>> cars{3,3}

ans =

2009 2010

2009 2010

>> cars{3,3}(1,:) = [2010, 2010];

>> cars{3,3}

ans =

2010 2010

2009 2010

23Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays: deleting

Deleting an element means replacing its current contents with empty vector

>> cars

cars =

{2x2 cell } [] []

[2x2 double] [2x2 double] []

[] [] [2x2 double]

>> cars{3,3} = []

cars =

{2x2 cell } [] []

[2x2 double] [2x2 double] []

[] [] []

24Cell arrays and structures

110

Page 111: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Cell arrays: deleting

we can also delete entire row(s) or column(s) from the cell array;

>> cars(3,:) = []

cars =

{2x2 cell } [] []

[2x2 double] [2x2 double] []

25Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures: definition

Structure is a data type with a name for the whole data structure in which individual elements (called fields) could be of different types (e.g., strings and double) and they are known by their name.

Structure groups together values that are logically related.

Structures are not arrays.

26Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures: how to create

Can be created one field at the time using assignment statements with dot operator:

>> cars.model = 'Toyota Camry Sedan';

>> cars.MSRP = 20445;

>> cars.fuel_econ = 9.05;

27Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures: how to create

… or all at once using struct function

>> cars = struct('model','Toyota Camry Sedan', 'MSRP', 20445,

'fuel_econ',9.05);

>> cars

cars =

model: 'Toyota Camry Sedan'

MSRP: 20445

fuel_econ: 9.0500

28Cell arrays and structures

111

Page 112: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Structure Arrays: definition

Structure array is an array of structures where each structure has the same names of fields, but the data stored in each field can differ.

29Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structure Arrays: how to create

Can be created one field at the time using assignment statements with dot operator

>> cars(1).model = 'Toyota Camry Sedan';

>> cars(1).MSRP = 20445;

>> cars(1).fuel_econ = 9.05;

>> cars(2).model = 'Ford Fusion Sedan';

>> cars(2).MSRP = 19695;

>> cars(2).fuel_econ = 9.80;

>> cars

cars =

1x2 struct array with fields:

model

MSRP

fuel_econ

30Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structure Arrays: how to create

… or all at once using struct function

>> cars(1) = struct('model','Toyota Camry Sedan', 'MSRP',20445, 'fuel_econ',9.05);

>> cars(2) = struct('model','Ford Fusion Sedan', 'MSRP',19695, 'fuel_econ',9.80);

>> cars =

1x2 struct array with fields:

model

MSRP

fuel_econ

31Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:viewing contents

>> cars(1)

ans =

model: 'Toyota Camry Sedan'

MSRP: 20445

fuel_econ: 9.0500

>> cars(1).model

ans =

Toyota Camry Sedan

>> cars(1).model(2)

ans =

T

32Cell arrays and structures

112

Page 113: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:viewing contents

field names can be listed using fieldnames function

>> fieldnames(cars)

ans =

'model'

'MSRP'

'fuel_econ‘

33Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:adding, modifying, deleting

structures/structure arrays are extended by assigning a new field

>> cars(1).year_production = 2009;

>> cars(1)

ans =

model: 'Toyota Camry Sedan'

MSRP: 20445

fuel_econ: 9.0500

year_production: 2009

>> cars(2)

ans =

model: 'Ford Fusion Sedan'

MSRP: 19695

fuel_econ: 9.8000

year_production: []

cars(2).year_production = 2009;

34Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:adding, modifying, deleting

values stored in fields can be modified using assignment

cars(1).year_production = 2010;

cars(1)

ans =

model: 'Toyota Camry Sedan'

MSRP: 20445

fuel_econ: 9.0500

year_production: 2010

35Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:adding, modifying, deleting

fields can be deleted with rmfield that returns a new

structure without the field, but it does not modify the original structure

>> rmfield(cars,'year_production')

ans =

1x2 struct array with fields:

model

MSRP

fuel_econ

>> cars

cars =

1x2 struct array with fields:

model

MSRP

fuel_econ

year_production

36Cell arrays and structures

113

Page 114: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:adding, modifying, deleting

fields can be deleted from the “original structure” in the following way

>> cars = rmfield(cars,'year_production')

>> cars =

1x2 struct array with fields:

model

MSRP

fuel_econ

37Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Structures and structure arrays:using data in structure arrays

fields can be used as arguments in MATLAB functions

you can use square brackets to process fields across multiple structures in an array

>> cars(1).MSRP

ans =

20445

>> cars(2).MSRP

ans =

19695

>> [cars.MSRP]

ans =

20445 19695

>> mean([cars.MSRP])

ans =

20070

38Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Nested structure arrays

A structure array may have another structure or structure array as one of its fields

>> cars(1).features = struct('ABS','yes' , 'keyless_entry','yes');

>> cars

cars =

1x2 struct array with fields:

model

MSRP

fuel_econ

features

>> cars.features

ans =

ABS: 'yes'

keyless_entry: 'yes'

ans =

[]

39Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Cell arrays vs. structures

Cell arrays do not use names for their elementsthey just number the elements, which could be inconvenient when we need to understand the meaning of the underlying data

Structures name their elements (fields)this could be inconvenient since it does not allow to loop over these elements

40Cell arrays and structures

114

Page 115: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Our problem from previous lectures:the cost to own

We will compute how long you need to own a car to make it economically advantageous to purchase a hybrid car vs. a car with a standard engine.

This time we will use structure arrays to store and pass the data.

Model MSRP Overall fuel economy

2010 Toyota Camry Sedan Hybrid $26,150 34 mpg = 6.92 L/100km

2010 Toyota Camry Sedan $20,445 26 mpg = 9.05 L/100km

2010 Ford Fusion Sedan Hybrid $27,950 39 mpg = 6.03 L/100km

2010 Ford Fusion Sedan $19,695 24 mpg = 9.80 L/100km

2010 Honda Civic Sedan Hybrid $23,800 42 mpg = 5.60 L/100km

2010 Honda Civic Sedan $16,455 29 mpg = 8.11 L/100km

2010 GMC Yukon Hybrid $51,185 22 mpg = 10.69 L/100km

2010 GMC Yukon $38,020 17 mpg = 13.84 L/100km

41Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Our problem from previous lectures:the cost to own

We store the data using structure array

cars(1) = struct('model','Toyota Camry Sedan', 'MSRP',20445, 'fuel_econ',9.05);

cars(2) = struct('model','Ford Fusion Sedan', 'MSRP',19695, 'fuel_econ',9.80);

cars(3) = struct('model','Honda Civic Sedan', 'MSRP',16455, 'fuel_econ',8.11);

cars(4) = struct('model','GMC Yukon', 'MSRP',38020,

'fuel_econ',13.84);

cars(5) = struct('model','Toyota Camry Sedan hybrid', 'MSRP',26150, 'fuel_econ',6.92);

cars(6) = struct('model','Ford Fusion Sedan hybrid', 'MSRP',27950, 'fuel_econ',6.03);

cars(7) = struct('model','Honda Civic Sedan hybrid', 'MSRP',23800, 'fuel_econ',5.60);

cars(8) = struct('model','GMC Yukon hybrid', 'MSRP',51185,

'fuel_econ',10.69);

save car_economy_study_inputs.mat cars;

42Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

Our problem from previous lectures:the cost to own

We store the data using structure array

[cars.model]

ans =

Toyota Camry SedanFord Fusion SedanHonda Civic SedanGMC YukonToyota Camry Sedan hybridFord Fusion Sedan hybridHonda Civic Sedan hybridGMC Yukon hybrid

[cars.MSRP]

ans =

20445 19695 16455 38020 26150 27950 23800 51185

[cars.fuel_econ]

ans =

9.0500 9.8000 8.1100 13.8400 6.9200 6.0300 5.6000 10.6900

43Cell arrays and structures

ENCMP 100

©2011 by ECE, UofACell arrays, structures, and structure arrays

Our problem from previous lectures:the cost to own

Problem statementUsing information about MSRP, fuel economy and price, and estimated yearly mileage, the program shall generate plots of the cost to own the hybrid and the standard cars as functions of the years/months when the car is owned, and it shall find the break-even point where the costs to own the standard and hybrid vehicles are equal.

Inputs: MSRP, fuel economy and price, and estimated yearly mileage

Outputs: Break-even point value, plot of the cost to own, and formatted

results saved to a text file.

OutlineStep 1. Load the MSRP and fuel economy from input file

Step 2. Prompt user for fuel price, yearly mileage, and model of the car

Step 3. Calculate cost to own & break-even point for inputs from 1 and 2

Step 4. Save formatted results into a text file (append to previous results)

Step 5. Plot the results

Step 6. Prompt the user to continue; if yes go to step 2, else terminate44

115

Page 116: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

The cost to own problem

car_economy_study (STEPS 1 and 6)

The main function that controls the flow of our program and calls other

functions

collect_user_inputs (STEP 2)

Inputs: cars structure array (that includes available models of the cars)

Outputs: fuel price, yearly mileage, and model of the car

calculate (STEP 3)

Inputs: fuel price, yearly mileage, and cars structure array (that includes

fuel economy, MSRP, model information)

Outputs: cost to own, break-even point

save_and_plot (STEPS 4 and 5; this function is not affected)

Inputs: fuel price, yearly mileage, cost to own, break-even point, and model

Outputs: text file with the formatted results, formatted plot of the results

45

Step 1. Load the MSRP and fuel economy from input fileStep 2. Prompt user for fuel price, yearly mileage, and model of the carStep 3. Calculate cost to own & break-even point for inputs from 1 and 2Step 4. Save formatted results into a text file (append to previous results)Step 5. Plot the resultsStep 6. Prompt the user to continue; if yes go to step 2, else terminate

Cell arrays and structures

ENCMP 100

©2011 by ECE, UofACell arrays, structures, and structure arrays

The cost to own problem

function [] = car_economy_study()% car_economy_study compares costs of standard and hybrid vehicles

% This function uses user-specified costs of 1 liter of gasoline

% and yearly milage to compare costs to own of standard and

% hybrid vehicles for a user-chosen model. The function provides

% text report in the car_economy_study.txt file and visualizes the

% results using a plot.

clear, clc

% load input data from file

load car_economy_study_inputs.mat; % stores cars structure array

test_end = 1;

while (test_end == 1)

% use collect_user_inputs function to prompt user for inputs

[fuel_cost,mileage,selected_model] = collect_user_inputs(cars);

% calculate the cost to own and break-even point

[cost,cost_h,break_even_point] = calculate(cars,fuel_cost,mileage,

selected_model);

% save and plot the cost and break-even point values

save_and_plot(fuel_cost,mileage,cost,cost_h,break_even_point,

cars(selected_model).model);

% prompt user to continue

test_end = input('\nType 1 to start over and 0 to terminate: ');

end46

ENCMP 100

©2011 by ECE, UofA

The cost to own problem

function [fuel_cost,mileage,model] = collect_user_inputs(cars)% collect_user_inputs prompts user for car model, fuel cost and mileage

% The function collects and returns inputs from the user including

% the desired model, the cost of 1 liter of gasoline and yearly mileage.

%

% collect_user_inputs(cars)

% cars -- a structure array with information about the available cars

% display and select the available models

model = -1;

while (model < 1 || model > length(cars)/2)

fprintf('\nModel number: model name\n');

for i=1:length(cars)/2 % loop over non-hybrid model names

fprintf('%2.0f: %s\n',i,cars(i).model);

end

model = input('Select the desired model number: ');

end

model = round(model);

% request other inputs from user

fuel_cost = input('Estimated cost of 1 liter of gasoline? ');

mileage = input('How many kilometers per year do you make? ');

47Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

The cost to own problem

function [cost,cost_h,break_even_point] = calculate(cars,fuel_cost,

mileage,model)

% calculate computes the cost to own and break-even point values

% The function uses the MSRP, fuel economy, cost of 1 liter of gas

% and yearly milage to calculate cost to own of regular and hybrid

% vehicles of the same model and to compute the break-even point where

% their costs are equal.

%

% calculate(cars,fuel_cost,mileage,model)

% cars -- a structure array with information about the available cars

% including their MSRP, fuel_economy, and model, for both

% standard and hybrid models.

% fuel_cost -- cost of 1 liter of gasoline

% mileage -- number of km to be driven per year

% model -- number of the user-chosen car model

% establish mileage scale in km per month

mileage_scale = 0:mileage/12:mileage*25;

% calculate the monthly cost to own using subfunction calculate_monthly_cost

cost = calculate_monthly_cost(cars(model).MSRP,mileage_scale,

cars(model).fuel_econ,fuel_cost);

cost_h = calculate_monthly_cost(cars(model+length(cars)/2).MSRP,

mileage_scale,cars(model+length(cars)/2).fuel_econ,fuel_cost);

continued on the next slide48

Cell arrays and structures

116

Page 117: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

The cost to own problem

% calculate the break-even point

break_even_point = -1;

for i=1:length(mileage_scale)

if (cost_h(i) < cost(i))

break_even_point = i;

break;

end

end

% subfunction that calculates the monthly cost to own

function monthly_cost = calculate_monthly_cost(MSRP,mileage_scale,

fuel_econ,fuel_cost)

monthly_cost = MSRP + mileage_scale.*(fuel_econ/100) * fuel_cost;

49Cell arrays and structures

ENCMP 100

©2011 by ECE, UofA

The cost to own problem

function [] = save_and_plot(fuel_cost,mileage,cost,cost_h,

break_even_point,model_name)

% save_and_plot plots the results and saves them in text file

% This function visualizes and stores the cost to own and

% break-even point values. A text report is saved in the

% car_economy_study.txt file and the results are shown using 2D plot

%

% save_and_plot(cost,cost_h,break_even_point,model)

% cost -- the calculated (per month) cost of the standard cars

% costh -- the calculated (per month) cost of the hybrid cars

% break_even_point -- month when costs of standard and hybrid are equal

% model_name -- name of the user-chosen car model

% save the results into a txt file

file_id = fopen('car_economy_study.txt','at');

fprintf(file_id,'Yearly cost to own %s assuming fuel at $%4.2f/L and

%6.0f km/year\n',model_name,fuel_cost,mileage);

fprintf(file_id,'Years owned Cost of hybrid Cost of standard\n');

for i=1:12:length(cost)

fprintf(file_id,'\t%2.0f \t\t\t %8.2f \t\t %8.2f \n',i/12,cost_h(i),

cost(i));

end

continued on the next slide

50Cell arrays and structures

ENCMP 100

©2011 by ECE, UofACell arrays, structures, and structure arrays

The cost to own problem

if (break_even_point ~= -1)

fprintf(file_id,'The hybrid model will be more economical after %2.0f

months\n\n',break_even_point);

else

fprintf(file_id,'The hybrid model will be more expensive over the

first 25 years\n\n');

end

fclose(file_id);

% plot the results

plot(1:length(cost_h),cost_h, 1:length(cost),cost)

title_text = sprintf('Cost to own the %s',model_name);

title(title_text), xlabel('Months owned'), ylabel('Cost to own')

grid

legend('Cost of hybrid model','Cost of standard model')

if (break_even_point ~= -1)

break_even_text = sprintf('Hybrid model is more economical after %2.0f

months',break_even_point);

else

break_even_text = sprintf('Hybrid model will be more expensive over

the first 25 years');

end

text(100,cost_h(1),break_even_text)51

ENCMP 100

©2011 by ECE, UofA

The cost to own problem

52

Step 1. Load the MSRP and fuel economy from input fileStep 2. Prompt user for fuel price, yearly mileage, and model of the carStep 3. Calculate cost to own & break-even point for inputs from 1 and 2Step 4. Save formatted results into a text file (append to previous results)Step 5. Plot the resultsStep 6. Prompt the user to continue; if yes go to step 2, else terminate

0 50 100 150 200 250 300 3501.5

2

2.5

3

3.5

4

4.5

5

5.5

6x 10

4 Cost to own the Ford Fusion Sedan

Months owned

Cost

to o

wn

Hybrid model is more economical after 168 months

Cost of hybrid model

Cost of standard model

0 50 100 150 200 250 300 3503

4

5

6

7

8

9

10x 10

4 Cost to own the GMC Yukon

Months owned

Cost

to o

wn

Hybrid model will be more expensive over the first 25 years

Cost of hybrid model

Cost of standard model

Cell arrays and structures

117

Page 118: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

10_CELL ARRAYS AND STRUCTURES

ENCMP 100

©2011 by ECE, UofA

Summary … of covered topics

• Cell arrays

• Structures and structure arrays

• Methods and functions that are used to create, visualize and modify the cell and structure arrays

53Cell arrays and structures

118

Page 119: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

Plots and Images: Advanced Topics

ENCMP

100

2©2011 by ECE, UofA

Overview

• Assign a handle to plots and adjust properties using handle graphics

• Learn how MATLAB handles three different types of image files

Plots & Images

ENCMP

100

3©2011 by ECE, UofA

Plotting Objects

In MATLAB the plotting information is organized in a

hierarchical way:

• figure – basic plotting object, can contain a number of different objects

• axes – are contained inside the figure; think of the axes as being layered on top of the figure window; the axes also can contain a number of different objects

• plot objects – drawn on top of the axes

Plots & Images

ENCMP

100

4©2011 by ECE, UofA

Plotting Objects

figure

axes layered

on the top of

the figure

plot drawn on the axes

Plots & Images

119

Page 120: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

5©2011 by ECE, UofA

Plotting Object Properties

Object properties are special values associated with and objet that control some aspect of how that object behaves.

Each property has a property name (usually a string) and an associated value

When object is created all of it properties are

automatically initialized to default values

Plots & Images

ENCMP

100

6©2011 by ECE, UofA

Plotting Procedure

When plot function is invoked MATLAB automatically

creates

• a figure

• an appropriate axis

• draws the graph (plot) on the axis

MATLAB uses default values for many of the plot object

properties. For example the first line drawn is always blue, unless the user specifically changes it.

Plots & Images

ENCMP

100

7©2011 by ECE, UofA

Object Handles

A handle is a “nickname” given to an object in MATLAB

We can assign a handle to

• Individual plots

• The figure window

• The axis on which we draw the plots

Plots & Images

ENCMP

100

8©2011 by ECE, UofA

Plot Handle

Assigning a plot a name (or a handle) allows us to easily ask MATLAB to list the plot object properties.

>>x = 1:100;

>>y = x.^2;

>>p_handle = plot(x,y)

The variable p_handle is the handle of the plot.

Plots & Images

120

Page 121: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

9©2011 by ECE, UofA

Plot Handle: example

Plots & Images

ENCMP

100

10©2011 by ECE, UofA

Function get

The get function can be used to examine at any time the

values of properties:

value = get(p_handle, ‘Property name’);

>> value = get(p_handle,’LineWidth’)

value =

0.5000

>> value = get(p_handle,'color’)

value =

0 0 1

Plots & Images

ENCMP

100

11©2011 by ECE, UofA

Plot Handle: get example

>> get(p_handle)

DisplayName: ''

Annotation: [1x1 hg.Annotation]

Color: [0 0 1]

LineStyle: '-'

LineWidth: 0.5000

Marker: 'none'

MarkerSize: 6

MarkerEdgeColor: 'auto'

MarkerFaceColor: 'none'

XData: [1x100 double]

YData: [1x100 double]

ZData: [1x0 double]

Plots & Images

ENCMP

100

12©2011 by ECE, UofA

Figure Handle

We can also specify a handle name for the figure window. For the window named figure 1:

>> f_handle = figure(1)

If you have not specify a handle name, you can ask MATLAB to determine the current figure with the gcf

(get current figure) command

Plots & Images

121

Page 122: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

13©2011 by ECE, UofA

Figure Handle

>> f_handle = figure(1)

>> get(f_handle) % or get(gcf)

Alphamap = [ (1 by 64) double array]

CloseRequestFcn = closereq

Color = [0.8 0.8 0.8]

Colormap = [ (64 by 3) double array]

CurrentAxes = [174.01]

CurrentCharacter =

CurrentObject = []

CurrentPoint = [0 0]

DockControls = on

FileName =

Plots & Images

ENCMP

100

14©2011 by ECE, UofA

Axis Handle

Just as we can assign a handle to the figure window and the plot itself, we can assign a handle to the axis using the gca function (get current axis )

>>h_axis = gca

Plots & Images

ENCMP

100

15©2011 by ECE, UofA

Axis Handle: example

>> h_axis = gca

>> get(h_axis)

ActivePositionProperty = outerposition

Color = [1 1 1]

DrawMode = normal

FontAngle = normal

FontName = Helvetica

FontSize = [10]

LineWidth = [0.5]

Plots & Images

ENCMP

100

16©2011 by ECE, UofA

Annotation Axes

In addition there is a transparent layer added to the plot,

used for annotation objects, such as:

• lines

• legends

• text boxes

Plots & Images

122

Page 123: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

17©2011 by ECE, UofA

Using Handlers to Manipulate Graphics

Use the set function to change the object properties

set requires at least three inputs

• object handle (plot, figure or axis)

• property name

• a new property value

Plots & Images

ENCMP

100

18©2011 by ECE, UofA

Using Handlers to Manipulate Graphics

Plots & Images

ENCMP

100

19©2011 by ECE, UofA

Property Editor

You can accomplish the same thing interactively using

the property editor and the property inspector

To invoke property editor:

View -> Property Editor

You can access all the properties if you choose Property

Inspector from the property editor pop-up window

Plots & Images

ENCMP

100

20©2011 by ECE, UofA

Property Editor

Plots & Images

123

Page 124: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

21©2011 by ECE, UofA

MATLAB Image File Functions

MATLAB includes two basic functions for displaying images stored as a MATLAB matrix

•image•imagesc (scaled image)

Before details about the functions and their application we explain how MATLAB ‘treats’ image files

Plots & Images

ENCMP

100

22©2011 by ECE, UofA

Image vs. Matrix

It is convenient to think of image data as a matrix. Each

element of this matrix represents a pixel of an image, and its value representing this pixel’s intensity (for grayscale images) or color. The matrix:

simple_image = [ 1 3 4 5 6 7 8 9 8;

1 2 3 4 5 6 7 8 9;

7 2 9 8 7 6 4 3 2];

represents an image 3x9 pixels. Each of the values is mapped into a color based on a color map.

Plots & Images

ENCMP

100

23©2011 by ECE, UofA

Color map

It is a color look-up table.

It may have any number of rows, but it must have exactly

3 columns. Each row is interpreted as a color, with the first element specifying the intensity of red light, the second green, and the third blue. Color intensity can be specified on the interval 0.0 to 1.0.

[0 0 0] is black, [1 1 1] is white,

[1 0 0] is pure red, [.5 .5 .5] is gray,

[127/255 1 212/255] is aquamarine.

Plots & Images

ENCMP

100

24©2011 by ECE, UofA

Color map>> colormap

ans =

0 0 0.5625

0 0 0.6250

0 0 0.6875

0 0 0.7500

0 0 0.8125

0 0 0.8750

0 0 0.9375

0 0 1.0000

0 0.0625 1.0000

0 0.1250 1.0000

Plots & Images

124

Page 125: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

25©2011 by ECE, UofA

image(simple_image)simple_image = [ 1 3 4 5 6 7 8 9 8;

1 2 3 4 5 6 7 8 9;

7 2 9 8 7 6 4 3 2];

with the color map from the previous slide is:

Plots & Images

ENCMP

100

26©2011 by ECE, UofA

imagesc(simple_image)simple_image = [ 1 3 4 5 6 7 8 9 8;

1 2 3 4 5 6 7 8 9;

7 2 9 8 7 6 4 3 2];

now index 4 represents color #25 from the color map

Plots & Images

ENCMP

100

27©2011 by ECE, UofA

Image Types

Intensity (or grayscale) images

Indexed images

RGB (or true color) images

Plots & Images

ENCMP

100

28©2011 by ECE, UofA

Intensity Images

Called also grayscale or scaled images (it means that images do not have information about colors, and assigning colors to different pixels is/can be done based on esthetics)

The colors in the image are determined by a colormap

Used mostly with the function imagesc – the values stored in the image matrix are scaled, and correlated to one of the maps

This approach works well when the displayed values of matrix does not correlate to an actual color

Plots & Images

125

Page 126: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

29©2011 by ECE, UofA

Intensity Image example: X-rays

X-ray images traditionally were produced by exposing photographic film to X-ray radiation.

Now, many X-rays are processed as digital images and stored in a data file.

We can manipulate that file however we want, because the intensity of X-ray radiation does not correspond to any particular color.

Plots & Images

ENCMP

100

30©2011 by ECE, UofA

Intensity Image example: X-rays

MATLAB ships with a built in sample file

called spine.

When you load the file, a matrix is created that represents the data collected

from a digital x-ray.

The colors are determined by scaling the

values stored in the matrix X, and using the default colormap (jet)

ENCMP

100

31©2011 by ECE, UofA

Intensity Image example: X-rays

A representation that looks more like a

traditional X-ray is obtained if we use a color map called map that is included in

the spine file .

This color map corresponds to a special color map called bone.

Custom color maps are not necessary to display intensity images

ENCMP

100

32©2011 by ECE, UofA

Determining Image Data Type

MATLAB includes a function, imfinfo, that will read

standard graphics files and determine what type of data is contained in the file.

For example: the file mimas.jpg was downloaded from the internet www.saturn.jpl.gov

Plots & Images

126

Page 127: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

33©2011 by ECE, UofA

>> imfinfo('mimas.jpg’)

ans =

Filename: 'mimas.jpg'

FileModDate: '25-Nov-2010 00:03:17'

FileSize: 45889

Format: 'jpg'

FormatVersion: ''

Width: 418

Height: 418

BitDepth: 8

ColorType: 'grayscale'

FormatSignature: ''

NumberOfSamples: 1

CodingMethod: 'Huffman'

CodingProcess: 'Sequential'

Comment: {}

Orientation: 1

XResolution: 72

YResolution: 72

ResolutionUnit: 'Inch'

Software: 'Adobe Photoshop CS Windows

'

DateTime: '2005:08:03 12:59:39 '

DigitalCamera: [1x1 struct]

ExifThumbnail: [1x1 struct]

Determining Image Data Type

Plots & Images

ENCMP

100

34©2011 by ECE, UofA

Grayscale Image example: Mimas

To read a file from a standard graphics format, such as jpeg, use the imread

function, and store the results with a

variable name such as IMG

Create the image using the imagesc

function, because we know that it is a “grayscale” image

The result is sometimes called a false

color image

ENCMP

100

35©2011 by ECE, UofA

Grayscale Image example: Mimas

Use the axis image command to

adjust the dimensions, and the colormap(gray) function to change

the image to black and white (grayscale)

ENCMP

100

36©2011 by ECE, UofA

Indexed Image

Where color is important, use an indexed image.

The matrix, instead of being a list of intensity values, is a

list of colors.

The image is created like a paint-by-number painting. Each element contains a number that corresponds to a color.

The colors are listed in a separate matrix, called a color map*.

A custom color map can be created for each image, or a built-in color map could be used

*The color map is an nx3 matrix that defines n different colors, by identifying the red, green and

blue components of each color.

Plots & Images

127

Page 128: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

37©2011 by ECE, UofA

Indexed Image example: mandrill

mandrill is a built-in file that ships with

MATLAB. It includes the image information, and a map of the appropriate

colors

The image function is used for data

stored in an indexed image

Until we specify a color map, the image is displayed using the default color map – in

this case jet.

ENCMP

100

38©2011 by ECE, UofA

Indexed Image example: mandrill

Custom color map

The axis image command is used to

adjust the image to the appropriate dimensions.

ENCMP

100

39©2011 by ECE, UofA

Indexed Image

It is important to recognize what kind of file you are

displaying, so that you can make the optimum choice of how to represent the image.

Files stored using the gif format are often stored as indexed images. If you use imfinfo – it does not give

you much information.

In this case use import wizard (double click on the file

name in the current directory – the wizard launches and suggests creations of two matrices: cdata – indexed image, and colormap – the corresponding color map)

Plots & Images

ENCMP

100

40©2011 by ECE, UofA

The import wizard can be used to create an indexed image matrix and color map from a GIF file.

Rename to a different name

such as map

Indexed Image: GIF file

128

Page 129: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

41©2011 by ECE, UofA

More examples …

There are a number of sample images built into MATLAB and stored as indexed images. You can access these files by typing

load <imagename>

The available images are: flujet, durer, detail, mandrill, clown, spine, cape, earth, gatlin

Each of these image files create a matrix of index values called X and a color map called map. For example:

load earth

image(X)

colormap(map)

You’ll also need to adjust the aspect ratio of the display and remove the axis.

axis image

axis off

Plots & Images

ENCMP

100

42©2011 by ECE, UofA

True color (RGB) images

The third technique for storing image data is in a three

dimensional file, mxnx3.

Recall that a three dimensional matrix consists of rows, columns and pages.

These image files consist of 3 pages, one for each color intensity; red, green or blue

Plots & Images

ENCMP

100

43©2011 by ECE, UofA

blue

rows

columns

pages

green

red

True color images use a multidimensional array to represent the color of each element

True color (RGB) images

Plots & Images

ENCMP

100

44©2011 by ECE, UofA

>> imfinfo('butterfly.jpg')

ans =

Filename: 'butterfly.jpg'

FileModDate: '26-Nov-2010 00:37:58'

FileSize: 42767

Format: 'jpg'

FormatVersion: ''

Width: 450

Height: 338

BitDepth: 24

ColorType: 'truecolor'

FormatSignature: ''

NumberOfSamples: 3

CodingMethod: 'Huffman'

CodingProcess: 'Sequential'

Comment: {[1x57 char]}

True color image: info example

Plots & Images

129

Page 130: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

11_PLOTS AND IMAGES

ENCMP

100

45©2011 by ECE, UofA

True color image: example

True color image of a butterfly – All of the color information is stored in a

three dimensional matrix.

Notice in the workspace window that

x is a 338 x 450 x 3 matrix – one

page for each color.

We don’t need to load a color map,

because the color intensity

information is included in the matrix. Even if we change a color map, the

colors stay the same.

ENCMP

100

46©2011 by ECE, UofA

Summary … of covered topics

•Handle Graphics:

• plotting objects and their properties

• functions set and get

•Image Files:

• three types: grayscale, indexed image, true colors

• functions image and imagesc

• color maps

Plots & Images

130

Page 131: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

12_IMAGE PROCESSING EXAMPLE

Image Processing: Example

ENCMP

100

2©2011 by ECE, UofA

Overview

•How to alter images using MATLAB:• how to identify threshold values

• how to apply those values to create a mask

• how to use a mask to “merge” two images (replace pixels from one image with pixels from the other image)

Image Processing: Example

ENCMP

100

3©2011 by ECE, UofA

Problem statement

In the image on the right,

the sky is almost white – we

want to make it blue:

pure blue, or

blue with clouds, or

Image Processing: Example

ENCMP

100

4©2011 by ECE, UofA

• Identify values of pixels that should be replaced

• Build a mask from those pixels

• Find a picture from which we take “replacement” pixels

• Perform the replacement operation

Procedure

Image Processing: Example

131

Page 132: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

12_IMAGE PROCESSING EXAMPLE

ENCMP

100

5©2011 by ECE, UofA

Procedure: identifying values of pixels that need replacement

•Pick a horizontal line from the original image that crosses some of the pixels you want to replace

•Display RGB values for those pixels

•Analyze the values and identify a unique value that will be used as a threshold for creating a mask

Image Processing: Example

ENCMP

100

6©2011 by ECE, UofA

Identifying values of pixels that need replacement: program% loading an original image

road = imread('road_white.jpg');

image(road)

axis image

% displaying R,G,B values of the specified horizontal line

% from the original image

% asking for a line's number

line_no = input('input a line number: ');

% picking up the R,G,B values from the image

red = road(line_no,:,1);

gr = road(line_no,:,2);

bl = road(line_no,:,3);

% plotting the R,G,B values of the specified line

figure

plot(red, 'r');

hold on

plot(gr, 'g');

plot(bl,'b');

Image Processing: Example

ENCMP

100

7©2011 by ECE, UofA

Identifying values of pixels that need replacement: program results

Image Processing: Example

ENCMP

100

8©2011 by ECE, UofA

Procedure: building a mask

•Write a program to identify pixels based on selected threshold values (sample threshold values could be 160 for each color: R (red), G (green), B (blue))

•The program should:• build a logical matrix mask (the same size like the original

image) with values true for each pixel with values above the

threshold, and false for each pixel with values below the

threshold

• identify area from the original picture for which pixel values will be replaced (modification of the logical matrix mask)

Image Processing: Example

132

Page 133: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

12_IMAGE PROCESSING EXAMPLE

ENCMP

100

9©2011 by ECE, UofA

Building a mask: program% asking for a threshold value

threshold = input('input a threshold value: ');

% identifying pixels with values above the threshold

% creating a 2D matrix with values: true - if above, false - if below

layer = (road(:,:,1)> threshold) & (road(:,:,2)>threshold) &

(road(:,:,3)>threshold);

% building a mask based on the threshold

mask(:,:,1)=layer;

mask(:,:,2)=layer;

mask(:,:,3)=layer;

% displying the mask

figure

image(mask)

axis image

% creating a mask for pixel replacement

% asking for boarder line (below that line there is no replacement)

boarder_line = input('input a boarder line: ');

mask(boarder_line:end,:,:) = false;

figure

image(mask)

axis image

Image Processing: Example

ENCMP

100

10©2011 by ECE, UofA

Building a mask: program results

Image Processing: Example

ENCMP

100

11©2011 by ECE, UofA

“Replacement” picture

Find a picture that you would like to use …

For example:

All those images are of the size of our original image.

Image Processing: Example

ENCMP

100

12©2011 by ECE, UofA

Procedure:replacement process

•Load picture with replacement pixels

•Replace pixels (based on the created mask)

Image Processing: Example

133

Page 134: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

12_IMAGE PROCESSING EXAMPLE

ENCMP

100

13©2011 by ECE, UofA

Replacement process: program

% loading a file with replacement pixels

sky = imread('blue_sky.jpg');

% making a copy of the original image

road_new = road;

% applying a mask

road_new(mask) = sky(mask);

% displying a modified image

figure;

image(road_new);

axis image;

Image Processing: Example

ENCMP

100

14©2011 by ECE, UofA

Replacement process: program results

Image Processing: Example

ENCMP

100

15©2011 by ECE, UofA

Replacement process: program results

Image Processing: Example

ENCMP

100

16©2011 by ECE, UofA

Summary … of covered topics

FUN !!!

Image Processing: Example

134

Page 135: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

Above and Beyond Programming

ENCMP

100

2©2011 by ECE, UofAAbove and Beyond …

Overview

• Computer revolution

• What is inside a computer

• “Onion model” of computing systems

• Different programming languages

• Software development

• Software errors

ENCMP

100

3©2011 by ECE, UofA

Computer Revolution: 1940s – the present

• The development of the programmable digital electronic computer during World War II started profound changes that now affect all aspects of technology and society.

• The changes caused by computers and computing are an on-going Computer Revolution, which began in earnest in the late 1950s and 1960s.

• The impact of the Computer Revolution is comparable to that of the Industrial Revolution (late-1700s to the early 1900s in Western Europe and North America; on-going in many parts of the world today).

• Such technological revolutions cause massive changes, which have both positive and negative effects.

Above and Beyond …

ENCMP

100

4©2011 by ECE, UofA

1940s: the First Electronic Computers

Colossus Mark 2

U.K., 1944 Electronic Numerical Integrator

and Computer (ENIAC)

U.S.A., 1947• Programmable code-breaking

computer

• 2400 tubes, ~4 m2 floor area

• Processed 5000 characters/s, limited by the speed of the paper tape reader.

• Used in military calculations (hydrogen bomb design, artillery tables, etc.).

• 17468 tubes, 150 kW, ~63 m2 floor area

• 100 kHz clock, 357 add/mults per sec

Above and Beyond …

135

Page 136: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

5©2011 by ECE, UofA

1947: the Solid-State Transistor

• Invented at Bell Labs in 1947 by William Shockley, John Bardeen, Walter Brattain.

• All three were awarded the Nobel Prize in Physics in 1956.

• Invented at Texas Instr-uments in 1958 by Jack S. Kilby.

• Kilby won the Nobel Prize in Physics in 2000 (along with another IC pioneer, Robert Noyce).

1958: the Integrated Circuit (IC)

Above and Beyond …

ENCMP

100

6©2011 by ECE, UofA

Moore's Law for ICs

In 1965 Dr. Gordon Moore (later a co-founder of Intel Corp.) noted that the number of transistors that could be economically manufactured on a single integrated circuit (IC) was roughly doubling every 12 months (after 1970, slowing down to every 18 months).

1,000,000

100,000

10,000

1,000

10

100

11975 1980 1985 1990 1995 2000 2005 2010

8086

80286

i386

i486Pentium®

Pentium® Pro

K 1 Billion Transistors

Pentium® II

Pentium® III

Year

Tra

ns

isto

rs / m

icro

pro

ce

sso

r

2015

Above and Beyond …

ENCMP

100

7©2011 by ECE, UofA

2010: Intel Core i7-980X (Extreme Edition)

• 3.33-GHz clock, dissipating 130 watts• 1.17 billion transistors forming six cores & L3 cache in 248 mm2

• 32-nm CMOS (the most advanced production process in 2010)• U.S. $999 in quantities of 1000 or more

Above and Beyond …

ENCMP

100

8©2011 by ECE, UofA

Revolutionary aspects of Computers (1)

• Speed: rate of calculation has been increased from tens of operations/second to billions of operations/second

• Compactness and reliability: computers have shrunk in physical size and increased greatly in reliability as the implementation technology has evolved:

• (19th cent.) mechanical cogs, shafts, punched cards

• (early 20th cent.) electro-mechanical relays

• (1920s to 1960s) electron tubes, cathode ray tube displays

• (1950s to early 1970s) discrete wires, transistors, resistors, capacitors, inductors

• (early 1960s to present) integrated circuits, Very Large Scale Integration (VLSI) chips

• (1990s to present) Microelectromechanical Systems (MEMS)

• (1990s to present) emerging nanotechnologies, quantum computing

Above and Beyond …

136

Page 137: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

9©2011 by ECE, UofA

Revolutionary aspects of Computers (2)

• Digital representation of information:

• All forms of information (e.g., numbers, letters, sound, images, video, algorithms) can be represented using sequences of discrete symbols or digits from a common finite-sized alphabet.

• In the binary (base 2) representations used by most digital computers, information is represented using sequences of only two symbols, called "0" and "1".

• Binary symbols are called binary digits or bits.

• Once information has been reduced to bits (e.g., has been digitized), it can be stored and preserved, communicated at high speed over possibly long distances, and processed directly by computers.

Above and Beyond …

ENCMP

100

10©2011 by ECE, UofA

Revolutionary aspects of Computers (3)

• Programmability: Digitized information is processed by sequences of instructions. These sequences are called algorithms or computer programs.

• Each instruction specifies a data movement and/or a a relatively simple data transformation step. Ex:

• Read input data stored at one particular storage location in a memory and hold in a fast register.

• Execute an operation on data in registers.

• Write the result(s) to specified fast registers and/or memory locations.

• The functionality of a computer can be "readily" changed by changing the program. There is no need to make physical changes to the computer.

Above and Beyond …

ENCMP

100

11©2011 by ECE, UofA

A Brief Intro. to Computer Architecture

Above and Beyond …

ENCMP

100

12©2011 by ECE, UofA

Layered Computer System Architecture

Computer Hardware

Operating System (OS)

ApplicationSoftwareCompilers &

Interpreters

User Programs

NetworkInterface

S/W

H/W

Users

Internet

UserInterface

Above and Beyond …

137

Page 138: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

13©2011 by ECE, UofA

Hardware Components

ALU CU

CPU

Secondary Storage

Input Devices OutputDevices

Memory

The Arithmetic Logic Unit handles all the mathematical and logical operations

The Control Unit decodes instructions and signals devices

The Central Processing Unit, the brain of the computer

Above and Beyond …

ENCMP

100

14©2011 by ECE, UofA

Hardware Components

• Memory: the subsystem that stores binary-encoded programs and binary-encoded data; note: all information stored in memory must be expressed with 0's and 1's.

• Central Processing Unit (CPU): This is the electronic "brain" that retrieves binary (base 2) instructions and data from the memory, and then executes the instructions to produce binary data results.

Above and Beyond …

ENCMP

100

15©2011 by ECE, UofA

Hardware Components

• Input devices: keyboard, mouse, joystick, data glove, touch-sensitive screen, microphone, as well as different types of sensors, for example, thermistor

• Output devices: screen, printer, speaker(s), plotter, as well as final control elements, for example, fuel flow valve

• Network Interface: Often a computer can be connected through a network interface and a local area network (LAN) to the world-wide Internet (the network cloud)

Above and Beyond …

ENCMP

100

16©2011 by ECE, UofA

How are Components Connected?

Components in a computer system are usually connected using a Bus:

CU

ALU

Processor/CPU

input

output

Memory (RAM)

Bus

A bus is a series of wires used to connect the different parts of a computer

Above and Beyond …

138

Page 139: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

17©2011 by ECE, UofA

Types of Memory

Most computers have:

• Primary storage (RAM—Random Access Memory)

• Secondary storage (hard disk drive)

Primary storage:

• Is usually fast electronic memory (in “chip” form)

• Can store a relatively limited amount of information

• Used to store programs and data the processor is currently working with

• Is volatile (it loses the data it is holding if power is turned off)

Above and Beyond …

ENCMP

100

18©2011 by ECE, UofA

Types of Memory

Secondary Storage:

• Is much slower to access data from than primary storage

• Can store much more data than primary storage

• Stores programs and data that the processor is notcurrently using

• Is non-volatile (it retains the information stored on it even when power is turned off)

Above and Beyond …

ENCMP

100

19©2011 by ECE, UofA

Types of Memory

Why have both types of memory in a computer?

• Speed: RAM is much faster than secondary storage

• Cost: it is too expensive to have only electronic memory in the system

• Capacity: secondary storage media can hold much more information (relates to cost as an issue)

• Persistence: primary storage loses information when you turn off your computer. It is unacceptable that data would have to be re-created every time a computer is switched on

Above and Beyond …

ENCMP

100

20©2011 by ECE, UofA

Software

• The CPU hardware reads the program instructions, one by one, and "executes" them. A special memory in the CPU, the Program Counter (PC) keeps track of the memory address of the next instruction to be executed.

• Examples of CPU program instructions:

� read some data from memory and write to a temporary storage location (a register) in the CPU

� add (or subtract) the contents of two CPU registers

� write the contents of a register to a memory location

� change the contents of the PC (change sequence of executed instructions)

Above and Beyond …

139

Page 140: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

21©2011 by ECE, UofA

Types of Software

• User Programs: Software developed for some particular special purpose by users.

• Application Software: Software packages designed and developed by other software engineers – commercial or "freeware" products.

• Compilers and Interpreters: Special programs that translate user programs from a human-readable form (e.g., MATLAB code) into a suitable binary form sothat they can be executed on the Central Processing Unit.

• Operating System (OS): A body of software that efficiently manages the use of computer resources, and that simplifies the appearance of the computer with respect to the users and the other software.

Above and Beyond …

ENCMP

100

22©2011 by ECE, UofA

Computing Systems

The "onion model" of a computer system

Above and Beyond …

ENCMP

100

23©2011 by ECE, UofA

Operating Systems

• Allocates computer’s resources to different tasks that the computer system must accomplish.

• Manages memory

• Manages secondary storage

• Handle input/output

• Facilitates interaction between the user and hardware by providing a convenient and efficient environment for selecting and executing software available on a given computer system.

• Provides system utilities (listing, copying and printing files, searching, editing, etc.)

Above and Beyond …

ENCMP

100

24©2011 by ECE, UofA

Application software

Programs that have been written to perform common operations such as:

• Word processors: Text processing (MS Word, Word Perfect)

• Spreadsheets: Working with data that can be displayed in a grid of rows and columns (MS Excel, Lotus 1-2-3)

• CAD tools: (computer aided design) Defining and Manipulating objects graphically (AutoCAD, Pro Engineer)

• Math tools: Performing advanced mathematical operations and graphing (MATLAB, Mathematica, Maple)

• Databases: Storing and Retrieving large amounts of data (dBASE, MS Access, Oracle, DB2, MySQL)

• Internet browsing: Accessing the World Wide Web (IE, Firefox, Netscape)

Above and Beyond …

140

Page 141: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

25©2011 by ECE, UofA

No Universal Off-the-Shelf Solution

Not every problem can be solved using a pre-defined application, or the application is not suitable for a particular need or environment.

Thus we also need to know how to write programs (our own application software) using languages understood by computers:

Programming Languages

Above and Beyond …

ENCMP

100

26©2011 by ECE, UofA

Programming Languages

Though all programming languages provide essentially the same features, there are many different ones.

Programming languages differ as there are vast differences in the types of input data, calculations needed, and output reports required by various applications.

They also differ in terms of levels or generations, and in ways to describe data and problems to be solved (programming paradigms).

Above and Beyond …

ENCMP

100

27©2011 by ECE, UofA

More on Programming Languages

• There is no one perfect programming language.

• Programming languages are a tool that are intended to facilitate the development of correct and efficient binary code for execution on a CPU for a class of problems.

• Some languages (e.g., MATLAB) are intended to facilitate the rapid development of relatively simple programs for engineering & scientific calculations, moderate-scale simulation, and data visualization.

• Other languages (e.g., Java) are intended to facilitate the development of code deployed over the Internet.

• And other languages (e.g., Fortran, C & C++) are intended for high-performance software, where efficiency and execution speed are the top priorities.

Above and Beyond …

ENCMP

100

28©2011 by ECE, UofA

Low Level vs. High Level Languages

Low Level Languages • (machine language, assembly language)

• Are tied closely to the design of the computer hardware.

• Programs in a low-level language run very fast but are very tedious to write.

High Level Languages

• (C++, Java, Python, Perl, Fortran, Pascal, Basic)

• Use instructions in English-like form.

• Programs are much easier to write and are portable in the sense that they can be used on different hardware platforms (sometimes with some modifications).

• The overhead of translating a high-level code into machine instructions is usually negligible for small programs given the power of today’s computers.

Above and Beyond …

141

Page 142: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

29©2011 by ECE, UofA

ASSEMBLY LANGUAGE:

LOAD A

ADD B

STORE C

MACHINE LANGUAGE:

1300042774

1400573417

1200274027

HIGH-LEVEL LANGUAGE:

C = A + B;

Obviously High Level Languages are much more desirable from a Programmers Perspective, they are easier to read and understand, and they require less coding then assembly languages.

Above and Beyond …

Low Level vs. High Level LanguagesENCMP

100

30©2011 by ECE, UofA

Interpreted vs. Compiled Languages

• There are two basic strategies for translating human-developed programs into the executable binary format.

• Programs in interpreted programming languages (e.g., MATLAB) are translated into binary format, line-by-line, as the program is executed on the CPU. This translation step occurs every time that each program line is encountered.

• Programs in compiled programming languages (e.g., C, C++) are translated once by compilers, before anything is executed, into binary format. Then the binary "object code" is executed on the.

Above and Beyond …

ENCMP

100

31©2011 by ECE, UofA

Pros and Cons of Interpreted Languages

Pros / Advantages:

• No need to run the compiler with the program before running the program.

• The program can be easily changed, and then re-run.

Cons / Disadvantages:

• The execution speed is slower for an interpreted program than with a compiled program.

• Each time a program line is encountered there is a small delay to translate the line into binary format.

• The delay penalty can be substantial if program lines are repeated executed (a fairly common situation).

Above and Beyond …

ENCMP

100

32©2011 by ECE, UofA

Novice Software Designers

• New software designers must learn to adapt to the constraints of the computer and the software.

• Computers have no "common sense" and will blindly execute the programs that they are given.

• Details are important! A computer does not know the difference between a "typo" and the intended text.

• When a program does not work as expected, 99.9999% of the time the fault will lie with the human designer.

• Software design requires a higher level of discipline and attention to detail than other kinds of engineering.

• Much time can be wasted by not following a systematic strategy for building and debugging software.

Above and Beyond …

142

Page 143: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

33©2011 by ECE, UofA

The Appeal of Software Design

• Software design is a creative process, a rather pure form of design that gives plenty of scope for innovation and ingenuity.

• Software (unlike other materials) does not wear out.

• Once a software feature has been added and verified to work properly, it will continue to work forever (as long as the surrounding software conditions do not change).

• Few (if any) other technologies improve as rapidly in performance and capabilities as do computers and computer software.

• Computer and software engineering offers a rapidly changing and exciting career in technology. The Computer Revolution shows no signs of slowing down.

Above and Beyond …

ENCMP

100

34©2011 by ECE, UofA

Structured Software Development

To maximize the chances of successful software, it is essential to use a structured development strategy.

1) Agree on the specifications of what the software is intended to do. This is a "contract" between the customer & developer.

2) Produce the design in stages, starting from an abstract high-level design, that shows only the largest software blocks and their interactions.

3) Refine the design of the larger blocks in terms of smaller blocks and their interactions. At each stage of this process of step-wise

refinement, more detailed block structure is added and their interactions are precisely defined. Finally, the blocks are small and simple enough to be directly implemented.

4) Verify the correctness of the software thoroughly against the correct behaviour given in the specifications. It is usually best to verify the smaller elements first, then build up in stages.

Above and Beyond …

ENCMP

100

35©2011 by ECE, UofA

Top-Down Designthen Bottom-Up Verification

Code / Programsin Programming Language

Specifications

Architecture /Top-Level Design

Detailed Design(typically many

levels withincreasing detail)

First-LevelCode Modules

Second-LevelCode Modules

Top-LevelInterface

.

.

.

.

.

.

Ste

pw

iseR

efin

em

ent

Bottom

-Up

Verific

atio

n

Above and Beyond …

ENCMP

100

36©2011 by ECE, UofA

Problems with Software Developers

• Humans underestimate the intellectual difficulty of designing correct software.

• Human software productivity has been found to vary by factors of as much as 10.

• Humans tend to be bad at keeping track of details. Psychologists have shown that we can keep track of roughly 7±2 chunks of information at any one time.

• Humans are not used to specifying calculations, processes and behaviours in full and complete detail.

• Humans tend to focus on the typical and average cases. They are bad at anticipating all unusual cases.

• Humans are terrible at accurately predicting how long it will take them (and others) to finish a software design.

Above and Beyond …

143

Page 144: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

37©2011 by ECE, UofA

The Nature of Software Development

• Software development is a challenging creative engineering activity.

• Software development requires a different kind of thinking, where we must imagine future algorithmic steps in time and where all possible situations must be anticipated and handled correctly.

• The changeability of software is both a blessing and a curse. It is very easy to get overwhelmed by the arbitrary complexity of computer programs. It is very difficult to produce correct computer programs

• Humans have much weaker abilities to keep track of details and algorithmic patterns than they think.

Above and Beyond …

ENCMP

100

38©2011 by ECE, UofA

Software Crisis

Scientific American: Software Chronic Crisis, W. Gibbs, Sep 1994, page 86http://www.di.ufpe.br/~java/graduacao/referencias/SciAmSept1994.html

1 of every 4 large software projects are canceled

Average project overshoots schedule by half

3/4 of all large systems are "failures" in that they do not operate as intended, or not at all

IBM Consulting survey of 24 leading companies • 55% cost more than expected • 68% overran schedules • 88% had to be substantially redesigned

Above and Beyond …

ENCMP

100

39©2011 by ECE, UofA

The New Field of Software Engineering

• To deal with the peculiar properties of software, and the new challenges of software development, the new field of Software Engineering has emerged.

• Software Engineering encompasses a body of recommended "best practices" that are intended to increase the chances that software systems will be correct and successful.

• Software Engineering takes into account the strengths and limitations of human engineers.

• There are interesting parallels between the develop-ment of structured human management systems and software engineering systems.

Above and Beyond …

ENCMP

100

40©2011 by ECE, UofA

Software Development Process(1) Requirements Specification

- determine what needs to be built- clear and unambiguous description of the problem

(2) Analysis- identify problem inputs and outputs- discover the problem constraints and relationships of variables

(3) Software Design- develop an algorithm- verify the logic of the algorithm- specify software structure (e.g. modules, interfaces)

(4) Implementation (Coding)- convert language-independent design into programs usinga programming language (e.g. C++)

(5) Testing- use manual and/or automated techniques to verify if the produced code

in fact satisfies all the specifications- white box (structural) and black box (functional) testing

(6) Maintenance (Usually the most expensive part!)- fix design errors (bugs – Y2K)- add features- translate to new programming language- change hardware platform (migration)

144

Page 145: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

41©2011 by ECE, UofA

The waterfall

model for

softwaredevelopment

Requirements

Specification

Analysisand Design

Implementation

(Coding)

Testing

Maintenance

Software Engineering came to the rescue

Above and Beyond …

ENCMP

100

42©2011 by ECE, UofA

Software Design and Algorithms

The analysis and design phases are generally more difficult than the implementation (coding) phase.

An algorithm must be developed - a clearly understandable finite sequence of steps

• to accomplish a task

• to transform inputs to outputs

• to get from an initial state to a final state

Algorithms can be expressed using • formulas

• flow charts

• pseudocode

Above and Beyond …

ENCMP

100

43©2011 by ECE, UofA

Errors

Syntax Errors

• Go to school I.

• I go to school.

Semantic (logical) Errors

• I ate my launch.

• I ate my lunch.

Speech (runtime) Errors

• I a-a-ate my lunch

(pronouncing the sentence wrong)

Above and Beyond …

ENCMP

100

44©2011 by ECE, UofA

Syntax Errors (Compiler Detects)

•Disp(‘The value is’, num2str(val));•Disp([‘The value is’, num2str(val)]);

Semantic (logical) Errors (User must Detect)

•cTemp = (fTemp - 22)/1.8;

•cTemp = (fTemp - 32)/1.8;

• Wrong: 122 Fahrenheit degrees equals 55.56 Celsius

• Right: 122 Fahrenheit degrees equals 50 Celsius

Above and Beyond …

Errors

145

Page 146: Computer Programming for Engineers - University of …smartynk/Resources/ENCMP 1… ·  · 2012-12-20Computer Programming for Engineers ... and scientific applications. Dave Cogdell,

13_ABOVE AND BEYOND

ENCMP

100

45©2011 by ECE, UofA

Runtime (execution) Error = 0;value = 0

Temp = (fTemp - 32) / value;

value = 1.8;

cTemp = (fTemp - 32) / value;

Can cause the program to breakdivision by zero is handled differently on different platforms

Since semantic errors occur at runtime, they are also often referred to as runtime errors

Above and Beyond …

ErrorsENCMP

100

46©2011 by ECE, UofA

Errors can be very stressful

Above and Beyond …

Errors

ENCMP

100

47©2011 by ECE, UofA

Reduce Errors• Follow Software Development Process

• >> Specifications >> Analysis >> Design

• Desk Check (manual checking for syntax and logical errors)

Syntax Errors• >> Implementation

• Compiler will catch them

• Easy to find and fix

Semantic and Runtime Errors• >> Testing

• >> Debugging

• Can be difficult to find and fix

Above and Beyond …

Avoid/Reduce ErrorsENCMP

100

48©2011 by ECE, UofAAbove and Beyond …

Summary … of covered topics

• History of computing and Moore’s law

• Computer components and different types of buses

• “Onion model” of computing systems

• Different types of programming languages (low and high level ones)

• Software crisis and software engineering

• Software development process (waterfall model)

• Software errors

146