Computational Modelling 102 (Scientific Programming) Tutorials

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

MATLAB Project: Getting Started with MATLAB

2.0 MATLAB Fundamentals

Introduction to MatLab. Introduction to MatLab K. Craig 1

PART 1 PROGRAMMING WITH MATHLAB

Introduction to Matlab

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

University of Alberta

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

Computer Programming in MATLAB

Computer Project: Getting Started with MATLAB

Matlab Programming Introduction 1 2

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

Introduction to Matlab

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

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

MATLAB Project: Getting Started with MATLAB

HERIOT-WATT UNIVERSITY DEPARTMENT OF COMPUTING AND ELECTRICAL ENGINEERING. B35SD2 Matlab tutorial 1 MATLAB BASICS

Introduction to MATLAB

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

1 Introduction to Matlab

MATLAB TUTORIAL WORKSHEET

Lab. Manual. Practical Special Topics (Matlab Programming) (EngE416) Prepared By Dr. Emad Saeid

Desktop Command window

Top bar items. Current folder should be shown. Command Window This has the the prompt >>

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

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

Introduction to MATLAB

Introduction to Engineering gii

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Dr Richard Greenaway

Introduction to MATLAB

Introduction to MATLAB

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

Getting started with MATLAB

LAB 1 General MATLAB Information 1

Introduction to Unix and Matlab

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

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

MATLAB SUMMARY FOR MATH2070/2970

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

AN INTRODUCTION TO MATLAB

EE 216 Experiment 1. MATLAB Structure and Use

A/D Converter. Sampling. Figure 1.1: Block Diagram of a DSP System

Getting To Know Matlab

The value of f(t) at t = 0 is the first element of the vector and is obtained by

Matlab Tutorial and Exercises for COMP61021

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Introduction to MATLAB

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

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

Introduction to Matlab

Getting Started with MATLAB

Finite Math - J-term Homework. Section Inverse of a Square Matrix

Math 2250 MATLAB TUTORIAL Fall 2005

To see what directory your work is stored in, and the directory in which Matlab will look for files, type

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

Chapter 1 Introduction to MATLAB

To start using Matlab, you only need be concerned with the command window for now.

Introduction to MATLAB

An Introduction to MATLAB II

x = 12 x = 12 1x = 16

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

Matlab Introduction. Scalar Variables and Arithmetic Operators

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Introduction and MATLAB Basics

Getting Started with MATLAB

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

MATLAB QUICK START TUTORIAL

Introduction to MATLAB

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

FreeMat Tutorial. 3x + 4y 2z = 5 2x 5y + z = 8 x x + 3y = -1 xx

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

Programming in Mathematics. Mili I. Shah

MATLAB Introductory Course Computer Exercise Session

Matlab and Octave: Quick Introduction and Examples 1 Basics

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

Laboratory 1 Octave Tutorial

INC151 Electrical Engineering Software Practice. MATLAB Graphics. Dr.Wanchak Lenwari :Control System and Instrumentation Engineering, KMUTT 1

General Information. There are certain MATLAB features you should be aware of before you begin working with MATLAB.

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Introduction to MATLAB

Getting started with MATLAB

Introduction to Matlab

Introduction to Matlab

Introduction to Scientific Computing with Matlab

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Chapter 2. MATLAB Fundamentals

Lab 1 Intro to MATLAB and FreeMat

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Introduction: The Unix shell and C programming

Short Version of Matlab Manual

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

Transcription:

COMO 102 : Scientific Programming, Tutorials 2003 1 Computational Modelling 102 (Scientific Programming) Tutorials Dr J. D. Enlow Last modified August 18, 2003.

Contents Tutorial 1 : Introduction 3 Tutorial 2 : Matrices 6 Tutorial 3 : Plotting 7 Tutorial 4 : M-files 8 Tutorial 5 : More M-files 9 Tutorial 6 : Vectors 10 Tutorial 7 : Three Planets 11 Tutorial 8 : X-windows 12 Tutorial 9 : Loops 14 Tutorial 10 : Arrays 15 Tutorial 11 : Comotank 16 2

COMO 102: Tutorial 1, 2003 3 Tutorial 1 : Introduction What is MATLAB? MATLAB is a high performance interactive program to help you with numeric computation and data visualisation. MATLAB is built upon a foundation of sophisticated matrix software for analyzing linear systems of equations. These tools allow you to solve problems in applied mathematics, physics, chemistry, engineering, finance, etc. - almost any application area that deals with numerical calculations. The MATLAB Window First go the View menu, select Desktop Layout, then Five Panel. You should see the following windows: Launch Pad Command History Workspace Current Directory Command Window The Launch Pad The Launch Pad provides easy access to documentation, demos and tools. The first entry represents default MATLAB functionality. Below this you will see entries like Image Processing Toolbox, which are extra packages that you can use. The Command History This keeps a record of each command you evaluate in the command window. Unlike Mathematica, modification of long series of commands in MATLAB is difficult unless M-files are used (script files). You will most often use the command window only to invoke your M-files. You can drag items out of the Command History into the Command Window, which saves typing them in again.

COMO 102: Tutorial 1, 2003 4 Workspace All data within MATLAB is stored in variables. MATLAB stores all variables as matrices. For example, a single number is stored as a 1 1 matrix. The MATLAB workspace contains all of the variables used during the current MATLAB session. The Workspace Browser gives you information about the variables and the functions in use, and allows you to double click on matrices to edit them in the Array Editor. Current Directory When using M-files you will want to set the current directory to your work directory. This sets where MATLAB looks for M-files, and also where it saves output by default. The Current Directory window shows the files within the current directory. The Command Window The command window is where you enter your commands. To access previous commands you can use the Command History window, or use the up and down arrow keys to scroll through previous commands. You can not directly edit previous commands within the command window! Matrices in MATLAB Matrices in MATLAB are entered in square brackets. Elements in a row are separated by spaces or commas, and the rows are separated by semi-colons (;). 1. Enter the following matrix in the command window at the input (>>) prompt: a=[1 2 3 ; 4 5 6 ]. 2. Check that the size of a, as reported in the Workspace window, is 2x3. 3. How much memory does the matrix a use? 4. Enter the 3x3 matrix b: b=[ 1 0 0 ; 0 0 1 ; 0 1 0 ]. 5. We multiply matrices in MATLAB with *. Try a*b. Is the answer correct? 6. Evaluate b*a. Can you explain MATLAB s output in this case? More matrices Enter the following matrices in MATLAB: 1 2 3 1. A 1 = 3 2 1 1 3 2 2. A 2 = 1 2 3 2 1 3 3. A 3 = 1 3 2 4. A 4 = [ 1 3 2 ]

COMO 102: Tutorial 1, 2003 5 Some Matrix Operations MATLAB uses * for matrix multiplication. We can add and subtract matrices with the + and - symbols. We can transpose a matrix by using the symbol (on the same key as "). Questions Use MATLAB to answer the following: 1. Calculate the transpose of each matrix given in Section More Matrices. 2. Calculate A 1 A 2. 3. Calculate A T 3 A T 4. 4. Calculate A 1 + A T 1. Scalars in MATLAB MATLAB handles scalars in the conventional way. Try the following: 1. 1+2 2. sqrt(2) 3. 2^3^2 (note: is this 2^(3^2) or (2^3)^2?) 4. 2 * [ 1 2 3 ; 4 5 6 ] Unusual Operations MATLAB also allows a significant number of unusual matrix operations, i.e. operations on matrices generally not used in mathematics. We will investigate some of these in the first exercise. Help Spend some time browsing MATLAB s help. simple function? Can you figure out how to plot a

COMO 102: Tutorial 2, 2003 6 Tutorial 2 : Matrices 1. Calculate by hand the matrix product A v where A = a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33, v = x y z 2. Write the following equations in the form A v = b. x + 7y + z = 3 4x + 5y + 8z = 1 x + 8y + 10z = 5 3. The 3 by 3 identity matrix is defined as I 1 0 0 0 1 0 0 0 1 Note that I B = B I = B for any square 1 matrix B. Verify by hand that I v = v. 4. Given a square matrix A, the inverse of A, written A 1, has the property that. A A 1 = A 1 A = I. The inverse does not always exist; examples of non-invertible matrices are: 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 0 1 2 3 4 5 6 7 8 9 Use MATLAB to check that the inverse does exist for the matrix A of question 2. Also attempt to invert one of the non-invertible matrices and observe the error message produced by MATLAB. 5. Use the following result to solve the system given in question 2 for x: A v = b A 1 A v = A 1 b I v = A 1 b v = A 1 b 1 A square matrix is a matrix that has the same number of rows as columns.

COMO 102: Tutorial 3, 2003 7 Tutorial 3 : Plotting 1. Plot the following functions in MATLAB over the domain x [ 10, 10]. (a) sin(x) with 100 sample points. (b) tan(x) with 100 sample points. (c) tan(x) with 10000 sample points, and also change the y-axis to show only y [ 10, 10]. Explain the behaviour you observe before and after modifying the y-axis. (d) sin(x) and cos(x), where sin(x) is drawn with an red line and cos(x) with green. 2. Plot sin(x), sin(2x), sin(3x) and sin(4x) all in one graph over the domain x [0, 2π]. Label the axes appropriately, insert a plot legend, and use distinctive colours and/or dashing for the different lines. Also enter a title for the plot. 3. Read the help on subplot: SUBPLOT Create axes in tiled positions. H = SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of small axes, selects the p-th axes for for the current plot, and returns the axis handle. The axes are counted along the top row of the Figure window, then the second row, etc. For example, SUBPLOT(2,1,1), PLOT(income) SUBPLOT(2,1,2), PLOT(outgo) plots income on the top half of the window and outgo on the bottom half. SUBPLOT(m,n,p), if the axis already exists, makes it current. Use subplot to show the graphs of sin(x), sin(2x), sin(3x) and sin(4x) in a 2x2 rectangular arrangement. For each of the four sub-graphs set the y-axis to show the range [ 1.5, 1.5], and also insert an appropriate plot title.

COMO 102: Tutorial 4, 2003 8 Tutorial 4 : M-files 1. (a) Write a function called myroots (in the mfile myroots.m ). For a quadratic of the form ax 2 + bx + c, your function should input the coefficients in a 1x3 matrix (i.e. [a, b, c]), and output the two roots in a 1x2 matrix. Your m-file should work whether the roots are real and distinct, real and repeated, or complex conjugates. (b) Test your function with the quadratic y = x 2 2x 2. (c) Test your function with a quadratic with a repeated real root. (d) Test your function with a quadratic with complex roots.

COMO 102: Tutorial 5, 2003 9 Tutorial 5 : More M-files 1. Write a function m-file named quadraticplot which does ALL of the following: (a) Accepts a vector coeff containing the coefficients a, b, c of the quadratic y = ax 2 + bx + c as its input. (b) Determines the roots x 1 and x 2 of the quadratic (where x 1 x 2 ). (c) Exits if the roots are complex, with the message Complex Roots!. (d) Plots the quadratic over the region [x 1, x2 + ], = 1 + (x 2 x 1 ) 5. (e) Draws blue circles at the roots. 2. Test your function on the following quadratics: (a) y = x 2 1 (b) y = (x + 3)(x 5) (c) y = x 2 + 1 (d) y = (x 10)(x 9)

COMO 102: Tutorial 6, 2003 10 Tutorial 6 : Vectors Consider a function which takes a vector v = (v 1, v 2,..., v n ) as input, and returns three scalars: The sum of the squares of the elements (i.e. v 2 1 + v2 2 +... + v2 n ). The sum of the cubes of the elements (i.e. v 3 1 + v 3 2 +... + v 3 n). The mean of the elements (i.e. Write this function in two ways: v 1 + v 2 +... + v n ). n 1. Using a single for loop. 2. Without loops of any kind.

COMO 102: Tutorial 7, 2003 11 Tutorial 7 : Three Planets 1. Copy the threeplanets.m file to your home directory. 2. Edit the code so that the initial speed is passed as an input parameter to the threeplanets function. 3. Use your previous answer to produce plots of the asteroids trajectory for the initial speeds of: 3 km s 1, 4 km s 1, 5 km s 1. 6 km s 1.

COMO 102: Tutorial 8, 2003 12 Tutorial 8 : X-windows In the start menu you should find X-Win Pro under Programs, which contains Xserver and Xstartup. Run Xstartup. You will be presented with the following dialog, although the default values may be different: Do the following: In Start Method select REXEC. In Host Name/ IP Address type in como.otago.ac.nz. In User ID enter your usercode as on your ID card (e.g. johsa118). In Password enter you ID number (e.g. 4159982). Click on the down arrow beside the text box for Command File, and select X11R6 from the drop down list.

COMO 102: Tutorial 8, 2003 13 Then click Execute. After clicking Execute you should see a window that looks something like this: This is an xterm (x-windows terminal), and is run by the remote server (como.otago.ac.nz). Commands that you enter in this window are handled by the server, not by the computer you are sitting at! The server is a much faster computer with plenty of memory and hard drive space. Some basic commands available to you are: ls mkdir mydirectory cd mydirectory rmdir mydirectory directory listing (shows the files in the current directory) makes a directory called mydirectory. changes the current directory to mydirectory. removes the directory called mydirectory. Special directories (folders) include:. The current directory.. The parent directory of the current directory ~ Your home directory For example, cd ~ will change the current directory to your home directory. As a general rule try to use lowercase letters without spaces or punctuation for directory names. Next do the following through X-windows: 1. Change to your home directory. 2. Create a directory called week8. 3. Make week8 the current directory. 4. Type pwd to see that the present working directory is /home/yourusercode/week8. Now you are ready to begin Exercise 8.

COMO 102: Tutorial 9, 2003 14 Background: Tutorial 9 : Loops If statements can take the following form: if ( d > 0 ) { printf("d>0!"); } else if ( d < 0 ) { printf("d<0!"); } else { printf("d==0!"); } For loops are of the following form: for( starting_condition ; test ; expression ) statement; The starting condition is executed first, then for each iteration of the loop statement is evaluated, followed by expression. The loop stops when test becomes false. For example, to print the numbers from 1 through to 10: int i; for ( i=1 ; i<=10 ; i++ ) printf("%d ",i); While loops are a little simpler: int i=1; while (i<=10) { printf("%d ",i); i++; /* add one to i */ } Tutorial Questions: 1. Write a program that outputs n! for each n from n = 1 to n = 10. 2. Write a function called sqroot which calculates the square root of x using the iterative method of Q1) of Exercise 5. Iterate until the approximation r satisfies r r x 0.0001 (note that the absolute value of a floating point number is calculated using the fabs function in C - read the man page on fabs for more info by typing man fabs on the command line). 3. Test your answer to question 2 by calculating the square root of 10 with sqroot.

COMO 102: Tutorial 10, 2003 15 Tutorial 10 : Arrays 1. Write a function with declaration void farray( double x[], double y[], double numvals ); where x represents the vector x, y represents the vector y and numvals is the number of elements in x (and in y). Your function should set the vectors x and y as follows: x is a set of evenly spaced points in the interval [0, 2π]. Each element of y is calculated from the corresponding element of x as follows: y i = max( sin(x i ), cos(x i ) ), where max(a, b) is equal to a if a > b and b otherwise. 2. Write a function with declaration void outputpoints( double x[], double y[], double numvals ); which outputs the points in x and y to the file xyvals.txt, using the same output file format as shown in lecture 10. 3. Write a main routine which uses your functions to create the xyvals.txt file with 100 output points. 4. Plot a graph of the data in xyvals.txt in MATLAB (see lecture 10).

COMO 102: Tutorial 11, 2003 16 Tutorial 11 : Comotank 1. Log in to COMO using XWinPro (or CYGWIN). 2. Make a week11 directory in your home directory on COMO and change into that directory. 3. Enter the following command: [j@como week11]$ tar zxvf /usr/local/comotank.tgz You should see a list of files being extracted to a directory comotank. 4. Change into the new comotank directory with cd comotank 5. Type ls to get a directory listing. You should see: [j@como comotank]$ ls bigmatch comotank tanks tankview 6. Type cd tanks to change into the tanks directory. 7. Type nedit sucky.c & to confirm that the source code for the sucky tank is available. 8. Compile the sucky tank (gcc -o sucky -Wall sucky.c generic.c). 9. Change back into the comotank directory with cd... 10. Start a match with four tanks using the following command:./comotank sucky bouncer findshoot tatie 11. Review the match with tankview. If the graphics are a little slow you might wish to try tankview stored.game fast, or even tankview stored.game fast fast. 12. Repeat the last two steps, this time with more tanks in the match.