Numerical Methods Lecture 1

Similar documents
MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Dr Richard Greenaway

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Introduction to MATLAB Programming

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

A very brief Matlab introduction

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

LAB 1 General MATLAB Information 1

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Math 2250 MATLAB TUTORIAL Fall 2005

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

MATH 3511 Basics of MATLAB

MEI GeoGebra Tasks for A2 Core

Introduction to Matlab

SF1901 Probability Theory and Statistics: Autumn 2016 Lab 0 for TCOMK

Computer Programming in MATLAB

ARRAY VARIABLES (ROW VECTORS)

Finding, Starting and Using Matlab

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

1 Introduction to Matlab

Introduction to Matlab

MATH 5520 Basics of MATLAB

Matlab and Octave: Quick Introduction and Examples 1 Basics

Introduction to Engineering gii

Dr Richard Greenaway

MatLab Just a beginning

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

Introduction to Matlab

PART 1 PROGRAMMING WITH MATHLAB

Introduction to MATLAB

George Mason University ECE 201: Introduction to Signal Analysis Spring 2017

Lab 1 Intro to MATLAB and FreeMat

Introduction to MATLAB Practical 1

Introduction to Matlab

Laboratory 1 Introduction to MATLAB for Signals and Systems

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

How to Use MATLAB. What is MATLAB. Getting Started. Online Help. General Purpose Commands

AMS 27L LAB #2 Winter 2009

McTutorial: A MATLAB Tutorial

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

A Guide to Using Some Basic MATLAB Functions

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

3+2 3*2 3/2 3^2 3**2 In matlab, use ^ or ** for exponentiation. In fortran, use only ** not ^ VARIABLES LECTURE 1: ARITHMETIC AND FUNCTIONS

1. Register an account on: using your Oxford address

Lecture 1 arithmetic and functions

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Exercises C-Programming

Summer 2009 REU: Introduction to Matlab

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

MATLAB. Devon Cormack and James Staley

What is MATLAB and howtostart it up?

2nd Year Computational Physics Week 1 (experienced): Series, sequences & matrices

Floating-point representation

Digital Image Analysis and Processing CPE

MATLAB Premier. Middle East Technical University Department of Mechanical Engineering ME 304 1/50

Introduction to MATLAB LAB 1

Guide to Planning Functions and Applications, Grade 11, University/College Preparation (MCF3M)

18.02 Multivariable Calculus Fall 2007

Introduction to Mathematical Programming

ELEMENTARY MATLAB PROGRAMMING

MATLAB INTRODUCTION. Risk analysis lab Ceffer Attila. PhD student BUTE Department Of Networked Systems and Services

Introduction to Matlab

MATLAB QUICK START TUTORIAL

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

Some elements for Matlab programming

LECTURE 0: Introduction and Background

General MATLAB Information 1

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

PreCalculus Summer Assignment

Prerequisites for Math 130

f( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

MATLAB Workshop Dr. M. T. Mustafa Department of Mathematical Sciences. Introductory remarks

MATLAB Project: Getting Started with MATLAB

University of Alberta

Introduction to MatLab. Introduction to MatLab K. Craig 1

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

A General Introduction to Matlab

Eng Marine Production Management. Introduction to Matlab

An Introductory Tutorial on Matlab

Introduction to Matlab

INTRODUCTION TO MATLAB PROGRAMMING Lec 1.1: MATLAB Basics

Introduction to GNU-Octave

Lecture 1: What is MATLAB?

What is log a a equal to?

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

AN INTRODUCTION TO MATLAB

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Computational Mathematics/Information Technology. Worksheet 2 Iteration and Excel

EGR 111 Loops. This lab is an introduction to loops, which allow MATLAB to repeat commands a certain number of times.

MBI REU Matlab Tutorial

MATLAB is a multi-paradigm numerical computing environment fourth-generation programming language. A proprietary programming language developed by

MATLAB Guide to Fibonacci Numbers

50 Basic Examples for Matlab

Transcription:

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