Numerical Methods Lecture 1 Basics of MATLAB by Pavel Ludvík
The recommended textbook: Numerical Methods Lecture 1 by Pavel Ludvík 2 / 30
The recommended textbook: Title: Numerical methods with worked examples: Matlab edition Authors: WOODFORD, Chris a Chris PHILLIPS Publisher: New York: Springer, c2012 Numerical Methods Lecture 1 by Pavel Ludvík 2 / 30
Basics of MATLAB Numerical Methods Lecture 1 by Pavel Ludvík 3 / 30
MATLAB = MATrix LABoratory MATLAB was devised by Cleve Moler in the late 1970 s to make numerical computing easier for students at the University of New Mexico. Many of the obstacles to using a computer for mathematics were removed. In a MATLAB program variables, whether real or complex numbers, vectors or matrices may be named and used as and when required without prior notification or declaration and may be manipulated according to the rules of mathematics. MATLAB spread to other Universities and in 1984 Cleve went into partnership with a colleague to set up a company called Mathworks to market MATLAB. Mathworks is now a multi-national corporation specialising in technical computing software. MATLAB and products built on MATLAB are used all over the world by innovative technology companies, government research labs, financial institutions, and more than 3,500 universities. Numerical Methods Lecture 1 by Pavel Ludvík 4 / 30
Windows in MATLAB and Their Function Numerical Methods Lecture 1 by Pavel Ludvík 5 / 30
Creating Variables and Using Basic Arithmetic 1. To create a single variable just use it on the left hand side of an equal sign. Enter the name of the variable to see its current value. Numerical Methods Lecture 1 by Pavel Ludvík 6 / 30
Creating Variables and Using Basic Arithmetic Exercise Enter the following commands on separate lines. 1. r=4 2. ab1=7.1+3.2 3. r 4. A=r 2 5. sol=ab1*(1+1/r) 6. ab1=sol (1/2) 7. CV2=10/3 8. x=1.5e-2 Numerical Methods Lecture 1 by Pavel Ludvík 6 / 30
Creating Variables and Using Basic Arithmetic Exercise Enter the following commands on separate lines. 1. r=4 2. ab1=7.1+3.2 3. r 4. A=r 2 5. sol=ab1*(1+1/r) 6. ab1=sol (1/2) 7. CV2=10/3 8. x=1.5e-2 Try to write several command on the same line separating them by a comma or a semi-colon. What is the difference? Numerical Methods Lecture 1 by Pavel Ludvík 6 / 30
Standard Functions MATLAB provides a large number of commonly used functions including abs, sqrt, exp, log and sin, cos and tan and inverses asin, acos, atan. Numerical Methods Lecture 1 by Pavel Ludvík 7 / 30
Standard Functions MATLAB provides a large number of commonly used functions including abs, sqrt, exp, log and sin, cos and tan and inverses asin, acos, atan. Exercise Use MATLAB to calculate the following. 1. x=sqrt(2) 2. A=sin(1.5) 3. a=sqrt(x 2+A 2) 4. y=exp(1/x) Numerical Methods Lecture 1 by Pavel Ludvík 7 / 30
Standard Functions MATLAB provides a large number of commonly used functions including abs, sqrt, exp, log and sin, cos and tan and inverses asin, acos, atan. Exercise Use MATLAB to calculate the following. 1. x=sqrt(2) 2. A=sin(1.5) 3. a=sqrt(x 2+A 2) 4. y=exp(1/x) Look up the entry Elementary Math in MATLAB s help. Numerical Methods Lecture 1 by Pavel Ludvík 7 / 30
Standard Functions Exercise 1. Find the longest side of a right angled triangle whose other sides have lengths 12 and 5. Use the Pythagoras Theorem. 2. Find the roots of the quadratic function 3x 2 13x + 4 using the standard formula. Exercise Try to find the values of constants π and e in MATLAB. Numerical Methods Lecture 1 by Pavel Ludvík 8 / 30
Vectors and Matrices The matrix is created by 2 3 1 A = 4 8 3 2 3 1 A = [2 3-1; 4 8-3; -2 3 1]. Numerical Methods Lecture 1 by Pavel Ludvík 9 / 30
Vectors and Matrices The matrix is created by Exercise 2 3 1 A = 4 8 3 2 3 1 A = [2 3-1; 4 8-3; -2 3 1]. 1. Create the row vector x = (4, 10, 1, 0). 2. Create the column vector y = ( 5.3, 2, 0.9, 1). 3. Create the matrix 1 7.3 5.6 2 B = 1.4 8 3 0. 2 6.3 1 2 Numerical Methods Lecture 1 by Pavel Ludvík 9 / 30
Vectors and Matrices 2 3 1 1 7.3 5.6 2 A = 4 8 3, B = 1.4 8 3 0 2 3 1 2 6.3 1 2 Find out what happens if you type A(1,2), A(:,1) and A(3,:). Figure out what mathematical operations can performed with matrices A and B. Numerical Methods Lecture 1 by Pavel Ludvík 10 / 30
Vectors and Matrices Exercise Write a linear system 3x 1 + 5x 2 + 7x 3 = 25, x 1 4x 2 + 2x 3 = 10, 4x 1 x 2 3x 3 = 1 in a matrix form as Ax = b and solve it using MATLAB (realize that a notion of a inverse matrix can be employed). Numerical Methods Lecture 1 by Pavel Ludvík 11 / 30
Vectors and Matrices Exercise Write a linear system 3x 1 + 5x 2 + 7x 3 = 25, x 1 4x 2 + 2x 3 = 10, 4x 1 x 2 3x 3 = 1 in a matrix form as Ax = b and solve it using MATLAB (realize that a notion of a inverse matrix can be employed). Use the command x=a\b and compare it with the previous result. Numerical Methods Lecture 1 by Pavel Ludvík 11 / 30
Defining Mathematical Functions In most situations, we will define the mathematical functions in the following way: Consider the functions f (x) = x 2 sin(2x), g(x, y) = x 2 + y 2 cos 2 (xy). You can define them by f=@(x)x^2-sin(2*x) g=@(x,y)x^2+y^2-cos(x*y)^2 Numerical Methods Lecture 1 by Pavel Ludvík 12 / 30
Plotting Command plot(x,y) x=[1 3 4 12] y=[-1 0 2-3] plot(x,y) grid on Command fplot(f,[a,b]) f=@(x) x^2-2*x g=@(x) sin(3*x) fplot(f,[-1 5]) hold on, grid on fplot(g,[-1 5], r ) Look up plot and fplot in help of MATLAB. Numerical Methods Lecture 1 by Pavel Ludvík 13 / 30
Plotting Data and Functions Exercises 1. Plot the functions y = x and y = sin(x) and y = cos(x) over the range [0, 2π] on the same graph but using different colours. 2. Plot the three dimensional surface defined by z = x 2 y 2 across the x y ranges [ 2, 2] on both axes. Numerical Methods Lecture 1 by Pavel Ludvík 14 / 30
Solution of Exercise 2 % establish a grid of points equally spaced at intervals of 0.1 across the range [x, y] = meshgrid(-2 : 0.1 : 2, -2 : 0.1 : 2); % establish z-values using element by element multiplication z = x.*x - y.*y % plot the surface surf(x, y, z); colorbar % show the colour scale. Numerical Methods Lecture 1 by Pavel Ludvík 15 / 30
M-Files On the whole entering MATLAB commands and statements line by line is too error prone for anything but very short, transitory programs. Programs under development and programs which are going to be used repeatedly are better stored as a sequence of commands in a file. Such files are called M-files. Numerical Methods Lecture 1 by Pavel Ludvík 16 / 30
M-Files On the whole entering MATLAB commands and statements line by line is too error prone for anything but very short, transitory programs. Programs under development and programs which are going to be used repeatedly are better stored as a sequence of commands in a file. Such files are called M-files. Exercise 1. Use the file menu to create an M-file. Enter a sequence of commands. Save the file using a name of your choice. Execute the newly created M-file. Edit the file if necessary to obtain successful execution, then close the file. 2. Re-open the M-file, make changes to the program and reexecute. Numerical Methods Lecture 1 by Pavel Ludvík 16 / 30
The colon Notation and the for Loop How the colon works k:n is equivalent to k, 2, 3, 4,..., n. (incrementing by 1) k:m:n is equivalent to k, k + m, k + 2m, k + 3m,..., n. (incrementing by m) We use the for construct to sum the first 10 integers (1, 2,... 10): addnumbers = 0; % initial total for i = 1 : 10; addnumbers = addnumbers + i; % running total end Numerical Methods Lecture 1 by Pavel Ludvík 17 / 30
The colon Notation and the for Loop Exercises 1. By making a small change to the program above, use MATLAB to find the sum of the even numbers 2, 4,..., 10. 2. The following series may be used to calculate an approximation to 2 x n+1 = x n 2 + 1 x n, n = 1, 2,..., x 1 = 1. Calculate x 1, x 2,..., x 7 and show convergence to 2. Numerical Methods Lecture 1 by Pavel Ludvík 18 / 30
The colon Notation and the for Loop The following code would be sufficient to solve problem no. 2: x(1) = 1 % first approximation for n = 1 : 6 x(n+1) = x(n)/2 + 1/x(n) % successive approximations end Exercise Devise an alternative, more economical (with respect to the computer memory) version which does not save intermediate results but simply displays and then overwrites the current estimate of 2 by the next estimate. Numerical Methods Lecture 1 by Pavel Ludvík 19 / 30
The colon Notation and the for Loop Exercises The Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13,... (each number is the sum of the two preceding numbers) relate to several natural phenomena. Use a for loop to print the first 20 Fibonacci numbers. Numerical Methods Lecture 1 by Pavel Ludvík 20 / 30
The if Construct In addition to the loop structure program flow may be controlled using if, else and elseif. Trace the basic if construct in the help of MATLAB. Numerical Methods Lecture 1 by Pavel Ludvík 21 / 30
The if Construct In addition to the loop structure program flow may be controlled using if, else and elseif. Trace the basic if construct in the help of MATLAB. Question What kind of logical conjunctions do you know? Numerical Methods Lecture 1 by Pavel Ludvík 21 / 30
Enter the code in a MATLAB program to verify the outcome. x = 2; y = 1; if x > 2; y = x; end; a = 1; b = 2; if a == 1; b = a + 1; end; u = 1; v = 2; w = -2; if (u ~= 0 & u < abs(w) ) u < 0; u = u + w; else u = u - w; end; Numerical Methods Lecture 1 by Pavel Ludvík 22 / 30
The if Construct Exercise In using the formula for the solution of a quadratic equation the discriminant b 2 4ac may be positive (indicating two real roots), zero (a double root) or negative (complex roots). Write MATLAB code to set a variable roots to 2, 1 or 0 depending on the value of the discriminant. Test the program using various values of a, b and c. Numerical Methods Lecture 1 by Pavel Ludvík 23 / 30
The if Construct Exercise In using the formula for the solution of a quadratic equation the discriminant b 2 4ac may be positive (indicating two real roots), zero (a double root) or negative (complex roots). Write MATLAB code to set a variable roots to 2, 1 or 0 depending on the value of the discriminant. Test the program using various values of a, b and c. Exercise Given a vector (or matrix) of dimension (m, n) use a for loop within a for loop to count the number of non-zero elements. Test your code on simple examples. Numerical Methods Lecture 1 by Pavel Ludvík 23 / 30
The while Loop The while loop repeats a sequence of instructions until a specified condition is met. It is used as an alternative to the for loop in cases where the number of required repeats is not known in advance. Trace the basic while construct in the help of MATLAB. Numerical Methods Lecture 1 by Pavel Ludvík 24 / 30
The while Loop The while loop repeats a sequence of instructions until a specified condition is met. It is used as an alternative to the for loop in cases where the number of required repeats is not known in advance. Trace the basic while construct in the help of MATLAB. Exercise Create a vector of numbers which contains one or more zeros. Construct a while loop to find the sum of the numbers up to the first zero. Numerical Methods Lecture 1 by Pavel Ludvík 24 / 30
Simple Screen Output and Keyboard Input Screen Output As an alternative to entering the name of a variable the function disp may be used to output a value or a string. The standard forms are disp(x) and disp( s ) where x is a variable and s is a string of alphanumeric and other characters. Numerical Methods Lecture 1 by Pavel Ludvík 25 / 30
Simple Screen Output and Keyboard Input Screen Output As an alternative to entering the name of a variable the function disp may be used to output a value or a string. The standard forms are disp(x) and disp( s ) where x is a variable and s is a string of alphanumeric and other characters. Keyboard Input The function input may be used to request user input. The standard form is x = input( request ). The user sees the character string request on the screen and enters number(s) from the keyboard to be allocated to the program variable x. Numerical Methods Lecture 1 by Pavel Ludvík 25 / 30
Simple Screen Output and Keyboard Input As part of an interactive program, use the following code to obtain the value of m and echo the input to the screen. The program asks for confirmation (Y or N) that the number is correct and if necessary repeats the original request. m = input( Enter the number of data values \n ); reply = input( Is that correct, answer Y or N\n, s ); while ~strcmp(reply, Y ) input( Enter the number of data values\n ); reply = input( Is that correct, answer Y or N\n, s ); end; disp( Thank you ); Numerical Methods Lecture 1 by Pavel Ludvík 26 / 30
Simple Screen Output and Keyboard Input Exercise Write a program to request a password from the user. Compare the reply with a stored string. If necessary repeat the request at most twice until there is an agreement. Numerical Methods Lecture 1 by Pavel Ludvík 27 / 30
User Defined Functions You can define your own function stored i an M-file. The function heading has the form: function [out1, out2,... ] = functionname (in1, in2,... ) and M-file has to be saved under the same name as is a name of the function. Example Sum of the series 1 + x + x 2 + + x n : function [result] = sumgp(x, n) if x == 1; result = n+1 % Check for the exceptional case. else result = (x^(n+1) - 1)/(x - 1) end Numerical Methods Lecture 1 by Pavel Ludvík 28 / 30
User Defined Functions Exercise Write a function MaxElement to find the largest absolute value of all elements of an array or vector. Test the function on simple examples. Numerical Methods Lecture 1 by Pavel Ludvík 29 / 30
User Defined Functions Exercise Write a function MaxElement to find the largest absolute value of all elements of an array or vector. Test the function on simple examples. Solution (One of Many): function [result] = MaxElement(v) result = 0; for i = 1 : length(v) if abs(v(i)) > result; result = abs(v(i)); end end Numerical Methods Lecture 1 by Pavel Ludvík 30 / 30