handout 1: variables and matlab script m-files

25
Handout 1: Variables and MATLAB script M-files Computer programs: high-level versus low-level How to create and run MATLAB programs Variables – Scalars Arrays (1-D and 2-D) Complex numbers Arithmetic operations Standard functions MATLAB workspace Input and output Examples

Upload: others

Post on 09-Dec-2021

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Handout 1: Variables and MATLAB script M-files

Handout 1: Variables and MATLAB script M-files • Computer programs: high-level versus low-level • How to create and run MATLAB programs • Variables

– Scalars – Arrays (1-D and 2-D) – Complex numbers

• Arithmetic operations • Standard functions • MATLAB workspace • Input and output • Examples

Page 2: Handout 1: Variables and MATLAB script M-files

What is a computer program?

Low-level languages provide direct control

of internal and external memory and the arithmetic logic unit (ALU).

E.g. Instructions to add two 8-bit numbers in 6502 microprocessor assembly language:

A computer program is a series of instructions and data that causes a computer to perform a particular task

The instructions are normally written in a programming language and then translated into the binary instructions (‘machine code’) that can be executed by the computer.

Machine code Assembler

10100101 LDA $60

01100000

01100101 ADC $61

01100001

10000101 STA $62

01100010

Memory

Clock

Databus

Addressbus Central Processing Unit

Internalmemory

ArithmeticLogicUnit

Instruct-iondecode

Programming languages can be characterised as low level or high level.

Page 3: Handout 1: Variables and MATLAB script M-files

Brief aside – chip art

Source: smithsonianchips.si.edu

MIPS R4400 microprocessor

Analog Devices 2175 DSP

Intel 4004

Page 4: Handout 1: Variables and MATLAB script M-files

High level computer languages Drawbacks with assembler: High level languages allow you to describe

tasks in forms that are problem oriented rather than computer oriented. Each statement in a high-level language performs a recognizable function and will generally correspond to many assembly language instructions.

e.g., addition of two numbers: A = B + C

Traditional high level languages (e.g. C, Fortran, Pascal)

– Normally need to compile (i.e., translate into machine code) and link (i.e., include required additional code from function libraries) before the program can run

– Fast execution times – Long software development times

More recent programming languages (e.g. MATLAB, Mathematica, Mathcad)

– Interpreted (no need to compile and link) – Integrated graphical output libraries – Interactive – Slower execution – Faster software development

–Computer oriented

–Huge software development times for anything other than very short programs

–Not portable between computer types

Page 5: Handout 1: Variables and MATLAB script M-files

Constants and variables Numbers are introduced into a computer

program either directly as constants or indirectly with the use of variables.

Constants: decimal numbers, e.g. 3147.6, 100

Variables: represents a memory location that is assigned a name

Examples: mass 10.3

volume 3.4

How do you set up variables? Use an assignment statement of the form

variable_name = constant

Examples: mass = 10.3

volume = 3.4

Number format: conventional decimal notation, or scientific notation which uses the letter e to specify a power-of-ten scale factor. Some examples of legal numbers are

3 -99 0.0001

9.6397 1.60210e-20 6.023e23

Memory locations

Useful tip! The use of variables, with sensible names, will increase the readability of your programs

Page 6: Handout 1: Variables and MATLAB script M-files

Assignment statement Note that the = sign does NOT mean the

same as the algebraic = sign. It means ‘take the value of the constant on the right hand side of the statement, convert it to a binary representation, and store the result in a memory location with the name on the left hand side’

Example 1: x = 5 x = 10

Algebraic interpretation: Two simultaneous equations with no

solution (no value of x can satisfy both) Computer program interpretation:

Example 2: n = n + 1

Algebraic interpretation: Equation with no solution (no value of n

can satisfy it) Computer program interpretation: Take the contents of the memory location

named n, add 1, and store the result in the same memory location (thereby overwriting the original value)

Assign the value 5 to the memory location called x

Assign the value 10 to the memory location called x (thereby overwriting the first value)

Page 7: Handout 1: Variables and MATLAB script M-files

How to create a MATLAB program (script M-file) To create a script M-file, first launch the MATLAB

application (click Start at bottom left, select MATLAB under All Programs menu)

A script M-file is a MATLAB program, i.e. a text file containing MATLAB instructions.

From the resulting MATLAB Command Window, Home tab, choose New Script

Page 8: Handout 1: Variables and MATLAB script M-files

How to create a script M-file (2) Save the program to a file, e.g.

\tut1\ex1a, using the Editor - File tab, Save As command.

Script M-files must end with the extension '.m', e.g. ex1a.m. MATLAB automatically adds this extension (the file will be named ex1a.m in directory tut1).

Note also that MATLAB commands can be typed interactively at the command line. This is not recommended for anything other than the simplest of problems because no permanent record is kept of what you did.

Enter the assignment statements in the M-file editor:

Page 9: Handout 1: Variables and MATLAB script M-files

How to run your script M-file

Two possibilities using Command Window:

1. (Recommended for beginners) Use the cd command to set the current directory, e.g. >> cd tut1

2. (Recommended where files exist in multiple locations) Use the addpath command, e.g. >> addpath tut1

Then type the name of the file (without the .m extension) at the MATLAB prompt, e.g. >> example1

A good way to develop numerical solutions is to keep the relevant M-file open within the text editor window. Changes can then be made to the M-file; it is saved and then run by typing the name of the file at the MATLAB prompt. What-if questions can be answered in this way in just a few seconds.

NB1: use the ‘up arrow’ key to recycle previous commands

NB2: the other type of M-files – called “function M-files” – will be dealt with in Handout 2.

To run program, tell MATLAB where it is - either by typing instructions into the Command Window (below), or using toolbar buttons (next slide).

Page 10: Handout 1: Variables and MATLAB script M-files

How to run your script M-file (alternative method) 1. Press ‘Save and Run’ button: 2. Save file when requested:

3. Click ‘Change Folder’:

Page 11: Handout 1: Variables and MATLAB script M-files

Arithmetic operations A more general version of the

assignment statement is as follows: variable_name = expression

where expression consists of arithmetic operations on constants and previously defined variables, e.g.

>>n = n + 1

>>density = mass/volume

MATLAB arithmetic operators are similar to standard algebraic form except for multiplication and exponentiation:

Important point when using previously-defined variables:

Operation Algebraic form MATLAB

Addition A + B A + B

Subtraction A - B A - B

Multiplication A × B A * B

Division A / B A / B

Exponentiation AB A ^ B

MATLAB is case sensitive, e.g. it assumes mass and Mass are two different variables.

Page 12: Handout 1: Variables and MATLAB script M-files

Precedence of operations MATLAB follows standard algebraic

precedence rules:

Be careful with ordering of operators, e.g. area = 0.5*base*(height1 + height2) and area = 0.5*base*height1 + height2 will give different answers! If you are unsure, use additional brackets.

Useful tips! 1. Break long expressions into multiple

statements, e.g. could be computed using these statements

(assuming x is a scalar): numerator = x^3 –2*x^2 + x – 6.3

denominator = x^2 + 0.05005*x - 3.14

f = numerator/denominator

2. If an expression is too long to fit onto one line, use … to extend onto the next, e.g.

numerator = x^3 –2*x^2 ...

+ x – 6.3

Precedence Operation

1 Parentheses, innermost first

2 Exponentiation, left to right

3 Multiplication and division, left to right

4 Addition and subtraction, left to right

14.305005.03.62

2

23

−+

−+−=

xxxxxf

3. Use the % sign to add comments: anything after % is ignored up to the end of the line

Page 13: Handout 1: Variables and MATLAB script M-files

Complex numbers No special handling for complex

numbers. For example: >> c1 = 1 - 2i

c1 =

1.0000 - 2.0000i

>> c2 = 2 + i

c2 =

2.0000 + 1.0000i

>> c3 = c1*c2

c3 =

4.0000 - 3.0000i

Useful tip! Note that since i means the square root of

–1, you are advised not to use i as an ordinary variable when you write MATLAB programs involving complex numbers

Page 14: Handout 1: Variables and MATLAB script M-files

Standard functions MATLAB provides a large number of

standard elementary mathematical functions, such as abs, sqrt, exp, and sin. There are also special functions that provide values of useful constants e.g. pi, i, nan, inf.

For a list, type: >>help elfun

or search for keywords using helpdesk: >>helpdesk

or consult the summary sheet handout.

output_variable_name =

function_name(input_variable_name)

where input_variable_name is the name of the memory location containing the input data,

output_variable_name is the name of the memory location to contain the output data, and

function_name is the name of the function. Examples: >>y = sin(x) >>alpha = log(beta) We deal with functions in more detail in

Handout 2.

For cases where there is one input parameter and one output parameter, the function is called by an assignment statement of the form:

Page 15: Handout 1: Variables and MATLAB script M-files

The MATLAB Workspace Variables can be listed with the who and

whos commands: >>who

Your variables are:

ans density mass volume

To delete all the existing variables from the workspace, enter

>>clear

Previous commands can be re-used by pressing the “up-arrow” key on your computer keyboard

To find the current value of a variable: >>mass

mass =

10.3000

Suppression of printing using a semicolon:

>>density = mass/volume;

>>

This is useful for ‘debugging’ your programs, i.e. finding the mistakes (‘bugs’) in them

Page 16: Handout 1: Variables and MATLAB script M-files

Arrays: why are they useful? Many quantities in engineering practice are intrinsically one- or two-dimensional. When these are

represented numerically, it is natural to store them in a one- or two-dimensional array of memory locations.

e.g. signal from a digital storage oscilloscope:

Arrays are given names just like scalars, e.g. time and voltage. In this example, each array is one-dimensional (a ‘row’ vector).

0.660 0.665 0.670

2.300 2.280 2.260

time

voltage

Operations can be carried out on the entire array at the same time, saving programming effort and reducing the length of your programs.

Page 17: Handout 1: Variables and MATLAB script M-files

Arrays: entering and extracting data Entering 1-D arrays

For example: >>x = [10 11 12]

x =

10 11 12

Entering 2-D arrays Rules are the same as for 1-D. Use a

semicolon, ; , at the end of each row.

For example: >>A = [1 2 3;4 5 6;7 8 9]

A =

1 2 3

4 5 6

7 8 9

Extracting data from arrays 1-D arrays: specify the position (called

‘index’) within the array using round brackets, e.g.

>>z = x(2)

z =

11

Row 1 Row 2 Row 3

Column 1 Column 2 Column 3

Separate the elements of a row with blanks or commas.

Surround the list with square brackets, [ ].

Page 18: Handout 1: Variables and MATLAB script M-files

Arrays: extracting data/the colon operator (1) Note that variables can be used as an

index, e.g. >>n = 2;

>>z = x(n); 2-D arrays: specify the indices within

round brackets in (row, column) order, e.g.

>>B = A(2,3) %means row 2, col 3

B =

6

>>y = x’

The colon operator The colon operator ‘:’ reduces the need for typing in two main ways:

1. Setting up arrays variable_name = a:b:c

sets up a 1-D array from a to c with increments of b. If b is omitted, it is assumed to be 1.

For example:

>>B = 1:5

B =

1 2 3 4 5

Useful tip! You can convert a 1-D row vector to a column vector – and vice versa – using the transpose operator ′, e.g.

Page 19: Handout 1: Variables and MATLAB script M-files

Arrays: the colon operator (2) >>theta = 0:pi/4:pi;

>>alpha = 100:-7:80

alpha =

100 93 86

2. Extracting portions of an array variable_name1 =

variable_name2(a:b:c)

sets up a new array (variable_name1) using those elements of variable_name2 which have indices from a to c with increments of b. If b is omitted, it is assumed to be 1.

E.g. >>C = B(2:2:4)

C =

2 4

e.g. rows 2 to 3, columns 1 to 2 of A: >> D = A(2:3,1:2)

D =

4 5

7 8

The colon operator can be used by itself as an index, meaning all the rows or columns.

e.g. row 2, all the columns of A: >>E = A(2,:) E =

4 5 6

Portions of 2-D arrays can be accessed in the same way, using expressions of this type for both row and column indices.

Page 20: Handout 1: Variables and MATLAB script M-files

Arrays: arithmetic operations Array operations

The list of operators includes:

+ addition

- subtraction

* matrix multiplication

.* element-by-element multiplication

./ element-by-element division

.^ element-by-element power

>> p = [1 2;3 4]

p =

1 2

3 4

>> q = [5 6;7 8]

q =

5 6

7 8

>> prod1 = p*q

prod1 = 19 22 43 50 >> prod2 = p.*q

prod2 = 5 12 21 32

Note the important distinction between matrix operations and element-by-element operation, e.g.

Page 21: Handout 1: Variables and MATLAB script M-files

Array functions >>y = sin(x)

will take the sine of all the numbers stored in the array x and store the results in an array called y of the same size.

The general expression for a function that returns more than one variable is:

[out1,out2,…,outn] =

function_name(in1,in2,…,inm) where in1,in2,…,inm are the m input

variables and out1,out2,…,outn are the n output variables. The sizes of the input and output arrays do not necessarily correspond to one another, but depend on the function.

Examples: >>[m,n] = size(A);

Returns number of rows and columns of array A in scalar variables m and n, respectively

>>C = zeros(m,n); Returns array C, of size m rows by n columns, all

elements equal to zero >>C = ones(m,n); Returns array C, of size m rows by n columns, all

elements equal to one >>s = std(X(1:100));

Calculates standard deviation of first 100 elements of X, result in scalar s.

>>C = inv(A);

Calculates inverse of matrix A, result in matrix C.

The elementary mathematical functions introduced earlier also work on arrays, e.g.

Page 22: Handout 1: Variables and MATLAB script M-files

Input and output (1)

Input refers to the transfer of data from a

peripheral device such as the keyboard or hard disk into the program memory. Useful functions and commands are:

1. The input function, e.g.: >>R = input('How many apples')

Prompts user to respond by printing to screen the text in quotation marks. User inputs a number at the keyboard, presses return, and the value is then stored in the memory location on the left of the assignment statement.

Similar (though more professional) effects can be achieved through the use of a graphical user interface.

2. The load command, which reads binary files containing matrices generated by earlier MATLAB sessions, or reads text files containing numeric data.

For example, suppose the text file matrix1.dat contains the numbers 16.0 3.0 2.0 5.0 10.0 11.0 9.0 6.0 7.0

>>load matrix1.dat

reads the file and creates a variable, matrix1, containing the data.

Files can be created by the MATLAB M-file editor, in Notepad, or by exporting data in text format from other applications such as Excel.

How can we get data into and out of our program efficiently (i.e. without typing directly into our M-file)?

Page 23: Handout 1: Variables and MATLAB script M-files

Input and output (2) Output refers to the transfer of data from

the program memory to a peripheral device such as the computer monitor or hard disk. One simple method of printing on the monitor is to remove the semi-colon at the end of an assignment statement. Other useful functions and commands are:

1. The save command. This preserves the contents of the workspace in a MAT-file that can be read with the load command in a later MATLAB session. For example

>>save August17th

saves the entire workspace contents in the file August17th.mat.

>>save August17th image1

saves just the variable named image1. >>save August17th -ascii

2. The fprintf command. This is used to

print data to screen or to disk with full control over the output format and giving you the chance to include helpful text messages. See the help pages for more details.

Saves data in text (so-called ‘ascii’) format, suitable for loading into other applications such as Excel.

Page 24: Handout 1: Variables and MATLAB script M-files

Arrays: example problem (1) Five measurements are made of two quantitities A and B, giving the

following set of results:

Measurement 1 2 3 4 5

A 6.25 6.68 7.71 9.11 9.92 B 2.43 1.92 1.43 0.87 0.43 Measurement error in A is σA = 0.2 Measurement error in B is σB = 0.1 What is the error in the quantities (A+B), (A–B), A×B and A/B?

Page 25: Handout 1: Variables and MATLAB script M-files

Arrays: example problem (2) C = A + B D = A – B E = A × B F = A / B

σC2 = σA

2 + σB2

σD2 = σA

2 + σB2

(σE / E)2 = (σA / A)2 + (σB / B)2

(σF / F)2 = (σA / A)2 + (σB / B)2

A = [6.25 6.68 7.71 9.11 9.92] B = [2.43 1.92 1.43 0.87 0.43] sigA = 0.2*ones(1,5) sigB = 0.1*ones(1,5) C = A + B D = A-B E = A.*B F = A./B sigC = sqrt(sigA.^2 + sigB.^2) sigD = sqrt(sigA.^2 + sigB.^2) sigE = E.*sqrt((sigA./A).^2 + (sigB./B).^2) sigF = F.*sqrt((sigA./A).^2 + (sigB./B).^2)

Error propagation rules: (See e.g. G. L. Squires, Practical Physics, 530.0724/SQU)

Model MATLAB solution: