Matlab study notes for beginners, Study notes of Matlab skills

Basic introductory codes and guides to using matlab.

Typology: Study notes

2016/2017

Uploaded on 09/06/2017

jasonsimm2252
jasonsimm2252 🇺🇸

4

(2)

1 document

1 / 26

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MATHS 162 MATLAB lecture 1.
Today’s Topics
Using MATLAB as a calculator.
Constants
Arithmetic operators and expressions
Elementary functions, help, format
Variables, reserved words,
Introduction to script files
Input
MATLAB is a computer language/application designed for scientific computation. It can be used in two ways,
interactively (like a calculator) or non-interactively (as a programming language).
Starting
Click on the Windows start symbol at the bottom left of the screen, click Programs from the menu that appears,
maths and stats, then move to click Matlab. 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 instruction. It does not matter if the cursor is not at the end
of the line.
Arithmetic Operators
The arithmetic operators in decreasing order of precedence are:
arithmetic operator operation performed
^raise to a power
/division
*multiplication
-subtraction
+addition
You often need to use brackets to make sure that the operations are carried out in the correct order.
Arithmetic Expressions
>>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
3. 60
2+3
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

Partial preview of the text

Download Matlab study notes for beginners and more Study notes Matlab skills in PDF only on Docsity!

MATHS 162 MATLAB lecture 1.

Today’s Topics

  • Using MATLAB as a calculator.
  • Constants
  • Arithmetic operators and expressions
  • Elementary functions, help, format
  • Variables, reserved words,
  • Introduction to script files
  • Input

MATLAB is a computer language/application designed for scientific computation. It can be used in two ways, interactively (like a calculator) or non-interactively (as a programming language).

Starting Click on the Windows start symbol at the bottom left of the screen, click Programs from the menu that appears, maths and stats, then move to click Matlab. 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 instruction. It does not matter if the cursor is not at the end of the line.

Arithmetic Operators The arithmetic operators in decreasing order of precedence are:

arithmetic operator operation performed ^ raise to a power / division

  • multiplication
  • subtraction
  • addition

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

Arithmetic Expressions

2* ans=

12/ ans=2.

2^ ans=

10-(1+3) ans=

Write in MATLAB

  1. 3^2 + 5
  2. 32+
  3. (^) 2+3^60

5. − 2 × 5 × − 7

6. 12 5+1−^3

8. ( 34 )^4

Elementary Functions Most of the usual mathematical functions are implemented 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 calculators). The log base 10 is log10.

Variables and Memory A variable is a labelled piece of computer memory.

s=5.

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

  • 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.
  • Reserved words are variable names it is best not to use. This is often because they are names of built-in functions.
  • A semicolon after a statement suppresses the output. For example, the statement x=23 will set the value of variable x to 6 and also show the result on the screen. However, x=23; still sets the value of x to 6, but does not show the result of the multiplication on the screen.

Example Find the area of a circle with radius 5cm.

r= A=pi*r^

Now let radius be 7cm.

r= A=pi*r^

MATHS 162 MATLAB lecture 2.

Today’s Topics

  • Strings and disp
  • Boolean expressions
  • if statements - flow control

Revision Exercises Write Matlab expressions to calculate:

  • 42 + 3 cos π 2

1 − π

  • 5 e^3
  • Write a Matlab script file to:
    • Prompt the user to enter the value of the variable r; and
    • Calculate the circumference of a circle of radius r.

Well Depth Formula

depth = (

g k

) × (time +

e−k×time^ − 1 k

g: acceleration due to gravity, g ≈ 9 .81. k: friction constant, k ≈ 0 .05 for a stone (roughly).

Write Matlab to set the values of g and k and then calculate the depth for a given time.

g=9. k=0. t=input(’How long did the stone take to reach the bottom of the well? ’) d=(g/k)(t+(exp(-kt)-1)/k)

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=’Course MATHS 162’;

The first character of string y above is y(1). The 7th to 13th characters inclusive are y(7:13).

length(y) gives the length of string y.

Note that because length is the name of a function, it is not a good idea to use it as a variable name.

Concatenation This is following one string by another.

x=’I am studying’ x = I am studying y=’Course MATHS 162’ y = Course MATHS 162 [x y] ans = I am studyingCourse MATHS 162

disp command disp(x) will display x, whether it is a number or a string. If x and y are as above, then use

disp([x y])

Examples disp command output disp(5.7) 5. disp(’Hello’) Hello disp(154) 60 disp(’154’) 15*

A script file example

greeting=’Hello.’; question=’What is your name?’; disp([greeting,’ ’,question])

Output Hello. What is your name? The ; after a statement suppresses the output.

Well Depth Formula in a Script File

% Program to calculate depth of well from % time a stone takes to reach the bottom. % Use g=9.81, k=0. g=9.81; k=0.05; time=2; depth=g(time+(exp(-ktime)-1)/k)/k; disp(’Depth of well is ’) disp(depth) disp(’metres’)

Output

Depth of well is

metres

Boolean Expressions

Boolean Expressions 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

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

Booleans 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

Summary We have the following three kinds if statements

  • if boolean expression some statements end
  • if boolean expression some statements else some more statements end
  • if boolean expression some statements elseif boolean expression some more statements else some more statements end

Examples

  1. 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 prompt the user to enter the number of drinks ordered and display the appropriate messages.

Sample Outputs You have ordered 20 drinks. Reduced to 10

You have ordered 5 drinks.

drink=input(’How many drinks? ’); disp(’You have ordered’) disp(drink) disp(’drinks.’) if drinks> drinks= disp(’Reduced to’) disp(drinks) end

  1. Write a script file to prompt the user to enter an integer, and then display whether the integer is zero, positive or negative.

n=input(’Enter an integer ’); if n> disp(’Positive’) elseif n< disp(’Negative’) else disp(’Zero’) end

  1. Grades are to be assigned as follows: A 80% - 100% B 65% - 79% C 50% - 64%. Write a script file to prompt the user to input a mark and display the appropriate grade. If the user enters a number greater than 100 or less than zero, display a message that the mark is invalid.

mark=input(’Enter the mark ’); if mark > 100 | mark < 0 disp(’Invalid mark’) elseif mark >= 80 disp(’A’) elseif mark >= 65 disp(’B’) elseif mark >= 50 disp(’C’) else disp(’Fail’) end

MATHS 162F MATLAB lecture 3.

Today’s Topics

  • for statement
  • while statement

Revision Examples

  • We started with 15 kg of apples. Write a script file to:
    • Prompt the user to enter how many kg have been used today;
    • Display how many were used, and how many are now left.

Remember that you cannot use more than you have left!

for statement

for variable= start :increment: finish some statements end

Note that the increment can be omitted in which case it defaults to one or it can be negative in which case the loop counts dow.

Example Write a script file to calculate the squares of the integers up to 20.

% A script file to print out the squares % from 1 to 20. for i=1: disp(i) disp(’squared is’) disp(i^2) end

We can also count up by twos (or threes etc.) as the following example shows.

Example Write a script file to repeatedly prompt the user for a student mark and display the student mark along with the grade, until a negative mark is entered. Grades are: A 80% - 100%, B 65% - 79%, C 50% - 64%.

We will need a while loop with a boolean expression to recognise the negative mark.

mark=input(’Enter a mark ’); while mark > 0 if mark > 100 disp(’Invalid mark’) elseif mark >= 80 disp(’A’) elseif mark >= 65 disp(’B’) elseif mark >= 50 disp(’C’) else disp(’Fail’) end mark=input(’Enter a mark (or 0 if finished) ’); end

Example Write a script file to keep a count of how many mobile phones are left. First prompt the user to enter the number available at the start. As they are sold, display each sale and update the number available. When all phones have been sold, display a message that all are sold.

phones_left=input(’How many phones are there? ’); while phones_left > 0 sale=input(’How many phones are being sold? ’)’ if sale > phones_left disp(’There are only’ disp(phones_left) disp(’Sale reduced to’) disp(phones_left) sales=phones_left end end disp(’All Sold’)

Example The following script file asks users to guess values of x for which x − cos(x) will be zero. The variable tol is used to indicate how far from zero is acceptable. Variable max_guess is used to set the maximum number allowed. (Why?)

disp(’* When is x-cos(x) is zero? *’) disp(’ ’) tol=1e-2; max_guess=8; y= ______ ; n=0; while abs(y)>tol & ______ < max_guess x=input(’Enter your guess ’); y=x-cos(x); disp(’Value is’) disp(y) n=n+1; end if abs(y)<=______ disp(x) disp(’is close enough’) disp(’Value is’) disp(y) else disp(’Your guess limit is reached.’) disp(’Bad luck!’) end

Suggested answers: Ist: verby=2*tol (to get the loop started). 2nd: n 3rd: tol

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=pihr^2/1000; p_l=p_c/vol;

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

We can use the function by typing [v,p]=can(12,3,1).

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 workspace for example.

Examples for Functions

  1. Write a function file to calculate the volume of chocolate required for the jaffas.

function V=choc(d,N) r=d/2; V=Npir^2;

  1. Write a function file with a student mark as the input variable, and the grade (as a character string) as the output variable.

function s=grade(mark) if mark > 100 | mark < 0 s=’Invalid’; elseif mark >= 80 s=’A’; elseif mark >= 65 s=’B’; elseif mark >= 50 s=’C’; else s=’F’; end

  1. Write a function file that returns the sum of the positive components and the sum of the negative com- ponents of the input vector.

function [p,n]=sumpn(a) % to find sum of positive and sum of negative components of a p=0; n=0; for i=1:length(a) if a(i) > 0 p=p+a(i); elseif a(i) < 0 n=n+a(i); end end

  1. Write a script file for the large jaffas that: (a) prompts the user to input the diameter (b) prompts the user to input the number (c) calls the function in Example 1 (d) displays the amount of chocolate required.

diam=input(’What is the diameter of the jaffas? ’); num=input(’How many jaffas are to be made? ’); vol=choc(diam,num); disp(’Volume required is ’) disp(vol)

MATHS 162 MATLAB lecture 5.

Today’s Topics

  • Vectors
  • Graphing
  • Element by element operations

Revision

  • Write a Matlab function file with input parameter n and output parameter r where

r =

∑^ n

i=

i^3.

Vectors A vector is a one dimensional array. Some examples are: [1,3,2,9,5], [-1 3 8 0 -2 1], 1:100, 1:0.1:10, linspace(0,10,6)

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. 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 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].

Example Write a function with parameters:

  • input parameter is a vector, v;
  • output parameters are:
    • w which is the first element of v
    • z which is the last element of v
    • s which is the sum of the elements of v

function [w, z, s] = xxx(v) w=v(1); z=v(length(v)); z=sum(v);

Element by Element Operations

Two arrays can be multiplied together element by element. 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 If 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].

v.+w and v.-w will give an error. Adding or subtracting arrays is done element by element anyway, so we do not need these operations.

v*w will give an error because we cannot do matrix multiplication with two row vectors.

v^2 will give an error because we cannot square a row vector using matrix multiplication.

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 = x^2 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 values. This means we want element by element squaring, not to multiply the vector x by itself in matrix multiplication.

So we write y=x.^2.

MATLAB makes plotting the vector of values in x against the vector of values in y very easy:

plot(x,y).

It is also easy to plot multiple sets of data on the same axes, for instance: plot(x,x.^2,x,sin(x))

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.

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.

Adding Labels

xlabel(’x’) ylabel(’cos x’) title(’A graph’)

Multiple Graphs

plot(x,cos(x),x,sin(x))

Alternatively

x=linspace(0,2pi,50); y=x+2cos(x); plot(x,y)

If we write our own functions that we might want to use for plotting we should make them suitable for vector input parameters.

Example Write a Matlab function to evaluate the function

f (x) =

2 x + 1 x + 3

e−x.

Write a script file to plot a graph of f using 50 values of x from 0 to 20. Be sure to use the function that is written above!

The function file will be:

function y=f(x) y=(2x+1)./(x+3).exp(-x);

The script file will be:

x=linspace(0,20,50); y=f(x); plot(x,y)

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] find A*v.

Av =

Answer: (^) 

Exercise Write Matlab statements to calculate (^) 

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). This gives us a vector.

Examples

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

Find C(1,:) and C(:,2). Answers: C(1,:)=[25,14, 0,29 ,21] and C(:,2)= [14;12].

Examples

  1. Write a function file with input parameter matrix A and output parameter v which is the first row of A as a column vector.

function v=firstrc(A) v=A(1,:)’;

  1. Write a function file to find the maximum element in a particular row of a matrix. Use the matrix and the number of the row as input parameters, and the set the output parameter to be the maximum element in that row.

function m=max_in_row(A,p) v=max(A(p,:));

whos This is the command to return the number and size of the variables in use.

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 matrices 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.

Example 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.

function w=absmax(K) w=sum(abs(K),2);

Example Suppose we have a matrix of marks for 3 assignments for a group of 8 students, such as  

How will we enter this matrix into Matlab?

Write Matlab statements to find:

  1. A row vector of the total marks for each student.
  2. A column vector for the highest marks in each assignment.
  3. How many got more than 20 marks for Assignment 1.
  4. How many marks (over all assignments) were below 12.
  5. A column vector of assignment means.

Answers: Enter the matrix as M=[25 14 0 29 21 18 27 30;19 12 10 28 18 27 10 26;26 18 16 25 20 29 29 28]

  1. sum(M,1)
  2. [max(M(1,:));max(M(2,:));max(M(3,:))]
  3. sum(sum(M<12))
  4. mean(M,2)

Example Write a Matlab function file with

  • input parameters A, a matrix, and n, an integer,
  • output parameter p where p = −1 if there is no column n in A; otherwise p is the maximum absolute value in column n of A

function p=maxabs(A,n); [q,r]=size(A); if n>r | n< p=-1; else p=max(abs(A(:,n))); end