


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Basic introductory codes and guides to using matlab.
Typology: Study notes
1 / 26
This page cannot be seen from the preview
Don't miss anything!



















MATHS 162 MATLAB lecture 1.
Today’s Topics
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
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
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:
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.
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
Revision Exercises Write Matlab expressions to calculate:
1 − π
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
Examples
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
n=input(’Enter an integer ’); if n> disp(’Positive’) elseif n< disp(’Negative’) else disp(’Zero’) end
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
Revision Examples
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
function V=choc(d,N) r=d/2; V=Npir^2;
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
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
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
Revision
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:
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
function v=firstrc(A) v=A(1,:)’;
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:
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]
Example Write a Matlab function file with
function p=maxabs(A,n); [q,r]=size(A); if n>r | n< p=-1; else p=max(abs(A(:,n))); end