# Maths 363 Matlab Primer

N/A
N/A
Protected

Share "Maths 363 Matlab Primer"

Copied!
24
0
0

Full text

(1)

### Maths 363 Matlab Primer

We will work through most of this in class but the best way to learn this is to try it on a computer. Note that you can find more detailed information on the course website and by using Matlab’s help.

### Part 1

• Using MATLAB as a calculator.

• Constants

• Arithmetic Operators

• Arithmetic Expressions

• Elementary Functions

• Help

• Variables, workspace, who, clear, reserved words

• A simple graph

• Character Strings

• Concatenation

• disp command

• format command

• Introduction to Script Files

• Better Looking Output

• Boolean Expressions

• Introduction to Flow Control - If Statement

(2)

MATLAB is a computer language/application designed for scientific computation.

### Starting

Click on the Windows start symbol at the bottom left of the screen, click Programs from the menu that appears, then move to cick Matlab and then again. This opens the Command Window where you can use MATLAB like a calculator.

### Prompt

When MATLAB is ready to accept a new instruction it shows a prompt >>.

### Enter

Press the enter key when you have typed in your in- struction. It does not matter if the cursor is not at the end of the line.

### Continuation of a Line

If your instruction is too long to conveniently fit on a single line you can break it after an operator by typ- ing three dots then using return and continuing your instruction.

### Constants

Some constants are:

5 -206 0.001 8.1468

pi 3.1638E-3 5.24E12

(3)

### Arithmetic Operators

The arithmetic operators in decreasing order of prece- dence are:

arithmetic operator operation performed

^ raise to a power

/ division

* multiplication

- subtraction

You often need to use brackets to make sure that the operations are carried out in the

correct order.

>>12/(1+3) ans=3

>>2*3 ans=6

>>12/5 ans=2.400

>>2^3 ans=8

>>10-(1+3) ans=6

### Write in MATLAB

1. 32 + 5 2. 32+5

(4)

3. 2+360 4. 60+32

5. −2 × 5 × −7 6. 12−35+1

7. 214 8. (34)4 9. 5π

### Elementary Functions

Most of the usual mathematical functions are imple- mented in MATLAB.

>> cos(0)

>> 6*sin(pi/2)

>> exp(1)

>> log(exp(3))

>> sqrt(9) Note:

• MATLAB uses radians, not degrees.

• The log is the natural log (often labelled ln on cal- culators). The log base 10 is log10.

### Help

If you know the name of the function that you want help on use the help command.

For example,

>> help log

(5)

will give you some notes on the function log.

### Variables and Memory

A variable is a labelled piece of computer memory.

s=5.6

The number 5.6 is stored in the computer memory and labelled.

• The workspace is the memory and variables that are in use. This can be saved.

• who lists the variable names in current use.

• whos lists the variables and how much memory they use.

• clear X clears the variable X.

• clear all clears all the variables.

• Reserved words are variable names that you cannot use.

• Matlab is case sensitive. That means that the upper case and lower case of a letter are different. For example, the variable called s is different from the variable called S.

(6)

### A Simple Graph

>> x=linspace(0,2*pi,50);

>> plot(x,cos(x))

The first line sets up a variable called x which is 50 equally spaced numbers starting with 0 and ending with 2π. The second statement plots the values in x along the horizontal axis and the cos of each value up the vertical axis.

>> xlabel(’x’)

>> ylabel(’cos x’)

>> title(’A graph’)

### Copying Previous Input Lines

The key ↑ will copy the previous command into the current line. Use it twice to get the one before etc.

### Character Strings

Variables can be used to store numeric values (eg -6.5e3) or strings (eg ’Hello’).

Note that the single quote marks are used for strings in MATLAB.

>> n=5;

>> y=’Maths 363’;

The first character of string y above is y(1).

The 7th to 9th characters inclusive are y(7:9).

length(y) gives the length of string y.

(7)

### Concatenation

This is following one string by another.

>> x=’I am studying’

x =

I am studying

>> y=’Maths 363’

y =

Maths 363

>>[x y]

ans =

I am studyingMaths 363

### format Command

MATLAB always calculates internally to 16 significant figures. Use format to control the number of decimal places in the output.

format short 4 decimal places (the default) format long 14 decimal places

format short e scientific notation with 4 d.p.

format long e scientific notation with 14 d.p.

Example

disp(5.55744525*2) 11.1149

format long e

disp(5.55744525*2)

1.111489050000000e+01

### disp Command

disp(x) will display x, whether it is a number or a string.

(8)

Examples

disp command output disp(5.7) 5.7000 disp(’Hello’) Hello disp(15*4) 60 disp(’15*4’) 15*4

### Script Files

A program is a sequence of statements that are per- formed in order. They are stored in a script file.

A file is the basic unit that the computer stores on mass storage (such as hard disk or floppy disk). Files can store pictures, or programs (such as MATLAB script files) or other data (such as text files).

To run a program either type the name of its file in the Command Window or use the Debug menu in its window and choose Save and Run.

### Relations

Relations are comparisons which are either true or false.

In MATLAB: false is represented by 0 true is represented by 1

(or any other non-zero number) Examples

(9)

relation result

6>3 true (or 1) 3>6 false (or 0) 7==4 false (or 0) 7~=4 true (or 1)

### Boolean Expressions

Relations may be combined using logical operators. Use brackets to make sure of the order of evaluation.

~ logical NOT changes to opposite truth value

| logical OR at least one relation is true

& logical AND both relations are true Examples

expression result

(6>3) & (4>2) true (or 1) 7==4 | 2<6 true (or 1)

~(2>4) true (or 1) (~(2>4)) | 2>1 true (or 1) (2<0)&((1>-1)|(4==2)) false(or 0) Quick Quiz

( (5>0) | (5<10)) &(2==3)

(~(5>0)) | ((1+3==4) & (5<12))

### Better Looking Output

Use function sprintf to produce strings which include numerical results.

For example, if depth is a variable equal to 18.98525 then

(10)

disp(sprintf(’Depth is %4.2f metres.’,depth)) The output would then be

Depth is 18.98 metres.

Boolean Expressions in IF statements x=5;

if (x>2)|(x<0) x=2;

end

Exercise

No more than 10 drinks may be served to one person.

If more than 10 are ordered, the number is reduced to 10 and a message printed out. Write a script file to check the variable drinks which is set in the command window and display the appropriate messages.

Sample Output

You have ordered 20 drinks. Reduced to 10.

You have ordered 5 drinks.

(11)

### Maths 363 Matlab Primer Part 2

• input statement

• rand function

• if statement

• if .. else statement

• if .. elseif ..else statement

• Introduction to vectors

• for statement

• While statement

• Functions

• More on Functions

• Introduction to 2 dimensional arrays

• More on Vectors (1 dimensional arrays)

• More on Matrices (two dimensional arrays)

### input statement

This is used to enter values for a MATLAB program. It includes a string which is used as a prompt so the user knows what to enter.

Example

x=input(’Enter a positive number ’);

When this statement is executed, the string

Enter a positive number will appear in the com- mand window. The user then types in a value, and this value is assigned to the variable x.

(12)

rand function

Gives a random number between 0 and 1.

### if statement

The simplest type is if boolean expression some statements

end

Example

p=input(’Enter a positive number ’);

if p<=0

disp(sprintf(’%4.2f: not positive’,p)) end

### Other if statements

• if boolean expression some statements

else

some more statements end

• if boolean expression some statements

elseif boolean expression some more statements

else

(13)

end

### Example

A coin is tossed. If the result is a head the computer wins. If the result is a tail the coin is tossed a second time and if it is a head the computer wins and if a tail the user wins. Write a script file to play this game and display who wins.

toss1=rand;

toss2=rand;

if toss1>0.5

disp(’Computer wins’) elseif toss2>0.5

disp(’Computer wins’) else

disp(’You win’) end

### Vectors

A vector is a one dimensional array of numbers.

Some examples are:

[1,3,2,9,5], [-1 3 8 0 -2 1],

1:100, 1:0.1:10, linspace(0,10,20)

We can find how many elements in a vector by using the function length.

length([1,3,2,9,5]) is 5.

length(1:0.1:10) is 91.

A vector of length 1 (ie just a number) is called a scalar.

(14)

The vector [] is the null vector. It has length zero.

We can refer to the element of a vector by using its index. For example, if we use the MATLAB statement v=[1,3,2,9,5];

then we can use v(3) to refer to the third element, which is 2.

We can use a vector for the index in order to refer to more than one element. For the vector above, v(2:4) refers to the second to fourth elements inclusive of v.

This will be [3,2,9].

Examples

Let w=[9,2,10,-5,0,-2,4,1]. Write down:

1. w(5) 2. 2:3:8 3. 1:2:8 4. w(2:3:8) 5. w(8:-3:2)

6. w(length(w):-1:1)

### for statement

The syntax is

for variable=vector some statements end

Example

Write a script file to calculate the squares of the integers

(15)

% A script file to print out the

% squares from 1 to 20.

for i=1:20

disp(sprintf(’%2.0f squared is %4.0f.’,i,i^2)) end

Now change the script file to calculate the squares of the odd numbers up to 21.

% A script file to print out the odd

% squares to 20.

for i=1:2:21

disp(sprintf(’%2.0f squared is %4.0f.’,i,i^2)) end

Now change it to display them backwards

% A script file to print out the squares

% backwards from 20.

for i=21:-2:1

disp(sprintf(’%2.0f squared is %4.0f.’,i,i^2)) end

Example

Write a script file to calculate the sum of the integers up to 100.

total=0;

for n=1:100

total=total+n;

end

disp(sprintf(’Sum up to 100 is %3.0f.’ total))

### while statement

(16)

The while statement is used to execute a loop while a given boolean expression is true.

The syntax is

while boolean expression some statements

end

Example

Write a script file which prompts the user for a number M and then computes and displays the integers and their squares while the square is less than M.

% Calculates squares while square is

% less than M

M=input(’Enter the maximum number ’);

k=1;

while k^2 < M

disp(sprintf(’%2.0f squared is %4.0f.’,k,k^2)) k=k+1;

end

The for statement is used when we know in advance how many times we want to execute a loop. For exam- ple, to evaluate

n

X

i=1

i2

we know that the loop must be repeated n times even if we do not know the value of n before we run the program. With the while statement we can test for desired condition each time we execute the loop.

(17)

cess until the user enters a zero, say.

Functions

function [ output ]= funct-name (input)

If there is only one output variable, you omit the [ ].

There may be no output variables.

For example,

function [y,z]= f(x)

The statements that follow the function header will cal- culate the output variables in terms of the input vari- ables.

The function header and statements are typed into a file. Each function is in a separate file.

Example

function [vol,p_l]=can(h,r,p_c)

%returns a vector containing the volume

%vol (litres) and price/litre p_l of can.

%Inputs are height h (cm), radius r (cm),

%price p_c (dollars).

vol=pi*h*r^2/1000;

p_l=p_c/vol;

This will be typed into a file and saved as can. It is important to use the function name as the file name.

We can use the function by typing can(12,3,1).

(18)

Use of Variables

A function communicates with the rest of the workspace only through the input and output variables.

Any other variables that you use inside the function are known only inside the function. They are not defined in the Command Window for example.

Example

function v=facts(n)

% function finds vector of

% factorials p=1;

v=[1];

for i=2:n p=i*p;

v=[v p];

end

Another Function

function [a,b]=first(w)

%w is a vector i=1;

while w(i)<=0 i=i+1;

end a=i;

b=w(i:length(w));

• What is the result of

(19)

• What does the function first do?

2-D Arrays - Matrices

We have studied 1-D arrays (vectors) which are like a list of numbers. The 2-D arrays go both across and down, like the matrices we study in mathematics.

Example The matrix

1 −5 −4

−2 7 0 5 0 −1

 can be written in Matlab by

A=[1 -5 -4; -2 7 0; 5 0 -1]

or

A=[1, -5 ,-4; -2 ,7, 0; 5, 0, -1]

The numbers in a row are separated by spaces or com- mas (as in a vector), and the end of the row is marked by a ;.

If we want to refer to the element in the 3rd row and the 1st column then we use A(3,1). Note that the row number is the first index and the column number is the second index.

If a matrix is multiplied by a vector in Matlab, then the result is the same as the usual matrix/vector multipli- cation.

If v=[1; 4; -2] then A*v will be [-11;26;7].

Exercise

(20)

Write Matlab statements to calculate

1 0 2 2 0 0 2 5 1

 3

−2 7

Picking out rows and columns

If we want to pick out just the first row of matrix A, then we use A(1,:). It picks out the components which have their first index as 1.

To pick out the second column use A(:,2).

Examples

C=[25,14,0,29,21;19,12,10,28,18];

Find C(1,:) and C(:,2).

Some Vector Functions

length returns the length of a vector (i.e. how many elements or components it has).

min and max returns minimum and maximum elements respectively of the vector.

(21)

prod returns the product of the elements in the vector.

transpose returns the transpose of the vector i.e. a row vector becomes a column vector and vice versa.

Also use v’.

Some Vector Operations

You can add and subtract vectors, and multiply vectors by scalars in the usual way.

If you multiply vectors together, i.e. v*w, then it is matrix multiplication that you do. This means that you can only multiply a row vector by a column vector (and the result is a scalar), or multiply a column vector by a row vector (and the result is a matrix). All other multiplications will give an error.

v=[1,3,5,7]; w=[2;4;5;6];

Find:

v*w w*v

Element by Element Operations

Two arrays can be multiplied together element by ele- ment. For example, for two vectors, v and w, v.*w is a vector of the products of the corresponding elements of v and w. The two arrays multiplied will need to have the same size and shape. Also called componentwise operations.

We can also take powers of arrays element by element.

Each element of the array is raised to that power to form the result.

Examples

(22)

v=[-5 0 2 1]; w=[9 1 5 2];

Then

v+w is [4 1 7 3].

v-w is [-14 -1 -3 -1].

v.*w is [-45 0 10 2].

v.^2 is [25 0 4 1].

Plotting

When we plot a graph, we make a vector of x values for the horizontal axis and then a vector of y values that correspond to these x values. For example, suppose we want a rough graph of y = x2 from x = −5 to x = 5.

We could use x=[-5,-4,-3,-2,-1,0,1,2,3,4,5]. To make the y vector we need to square each of these x val- ues. This means we want element by element squaring, not to multiply the vector x by itself in matrix multi- plication. So we write y=x.^2.

Most of the built in functions in Matlab, such as sin and cos, can be used with vectors or matrices. The function is applied to each element. If we write our own functions that we might want to use for plotting we should make them suitable for vector input parameters.

Boolean Expressions with Vectors

We can use Boolean expressions to pick out elements of vectors which satisfy Boolean expressions.

For example, if r=[7,-4,0,6,-2,1],

then r>0 is [1,0,0,1,0,1]. It shows the positions of the elements of r which are positive.

(23)

Some Matrix Functions

size returns the dimensions of a matrix (i.e. how many rows and columns it has).

sum returns the sum over rows or columns.

sum(A,1) is a vector of the sums of the columns.

sum(A,2) is a vector of the sums of the rows.

prod as for sum but with products.

transpose returns the transpose of the matrix, i.e. a rows become columns and vice versa.

Some Matrix Operations

You can add and subtract matrices, and multiply ma- trices by scalars in the usual way.

If you multiply two matrices together then it is matrix multiplication and the number of columns of the first matrix must equal the number of rows of the second.

If you want the power of a matrix then the matrix must square, i.e. the number of rows equals the number of columns.

Matrices can also be multiplied together, or powers may be evaluated, element by element as for vectors.

Examples

Write a Matlab function to evaluate the function f(x) = 2x + 1

x + 3 e−x.

Write a script file using the above function to plot a graph for f using 50 values from x = 0 to x = 20.

(24)

Write a function with input parameter a matrix K. The output parameter will be a column vector of the sum of the absolute values of the elements in each row.

Special Matrices diag([1,3,-2,7])=

eye(4)=

ones(2)=

ones(2,1)=

zeros(2,3)=

References

Related documents

disadvantage have special resonance for the Australian Aboriginal community, where the construct, the best interests of the child, has been applied and has resulted in an

INTRODUCTION: The Vulnerable Children (VC) Act 2014 amended section 13 (s13) of the Children, Young Persons and their Families (CYP&amp;tF) Act 1989 to re-emphasise the principle

The Swedish school authorities have drawn attention to this work and designated the school ‘the best school in Sweden working for equal value 2008’. Student empowerment, child’s

The majority of private land in the MRA is peri-urban land located outside of rural villages.. The primary determinant of the market value of peri-urban lands is likely to

For each customer in a scenario, output the customer number followed by the value of their purchases, separated by a space, on a single line.. If a product

The total ABC contribution to Australian screen drama, combined with approximately \$125 million in external funding, delivered up to \$244 million in production value to

Sessional Com m ittee on the Environm ent 79.. A strong research and development effort, particularly into the integration of control methods, is essential to the

If you want to restore the old behavior, set this option to old, but note that then you can neither change the amounts for a given number of persons nor change the unit of \cutext

If you need to use the optional argument of \DTLforeach , you will first have to iterate through the database to count up the number of rows which meet the condition, and then

It takes two arguments — the first is the character you want to turn into a shortcut, the second is the macro code that will be executed when that character is encountered. If

• Write a Matlab script file which prompts the user to enter a matrix and then displays how many rows and columns in the matrix. • During a given week, the maximum temperature is to

• Additional High Conservation Value Vegetation (AHCVV) means areas of vegetation which were found during ground-truthing which would otherwise meet the definition of Existing

Vessel biofouling is a major pathway for the introduction of non-indigenous marine organisms into New Zealand territorial waters, some of which may be harmful

(3) The Committee shall examine only those accounts of receipts and expenditure of the Northern Territory and reports of the Auditor-General for financial years commencing after

Madam CHAIR: Mr Khattra says that you stopped allowing him to drive your taxi because he was a witness at the inquiry, the Public Accounts Committee, in to the taxi industry, what is

Ms LAWRIE (Leader of Government Business): Madam Speaker, I move – That, the Assembly refer the following matters to the Standing Orders Committee for inquiry and report to

In my opinion the financial report gives a true and fair view of the financial position of the Surveyors Board of the Northern Territory of Australia as at 30 June 2016, and of

Benzene (ppb) change in annual max 1-hour (MDA1) ground level concentrations from Scenario 2 due to future industry (S3-S2) for a subset of the CAMx 1.33 km domain centred over

The number as changed has effect in place of the number 88 in subsection (1). Operable on all current runways – recommended for review to relax restrictions. Site operators

5.15 At the time of Mr C’s requests for access to the NDIS, the NDIA did not have any policy or guideline dealing specifically with incarcerated individuals and access to the NDIS.

searching) if heuristic is consistent then the first time you hit a state you have found the optimal path to it and you can throw away all the later paths to it. • If the heuristic

31702 Mr Thomas Drach Yes Tasman District Resident Upper Moutere. 31703 Ms Paula Holden

existence. In making such an estimate, the Government Printer was requested to take as understood that each author body would have its report printed by the