Programming 1. Script files. help cd Example:

Similar documents
MATLAB Introduction to MATLAB Programming

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Matlab Tutorial and Exercises for COMP61021

Matlab Tutorial for COMP24111 (includes exercise 1)

Programming in Mathematics. Mili I. Shah

Introduction to Matlab

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

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

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

1 Introduction to Matlab

Mechanical Engineering Department Second Year (2015)

Matlab Programming Arrays and Scripts 1 2

Math 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau)

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

MATLAB primer for CHE 225

Matlab Tutorial 1: Working with variables, arrays, and plotting

1. Register an account on: using your Oxford address

MATLAB SUMMARY FOR MATH2070/2970

Introduction to Matlab

Introduction to Scientific Programming in MATLAB

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

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

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

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

PART 1 PROGRAMMING WITH MATHLAB

An Introductory Tutorial on Matlab

7 Control Structures, Logical Statements

QUICK INTRODUCTION TO MATLAB PART I

Introduction to MATLAB

Worksheet 6. Input and Output

Chapter 1 Introduction to MATLAB

CSE/Math 485 Matlab Tutorial and Demo

Introduction to MATLAB LAB 1

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

MATLAB Tutorial III Variables, Files, Advanced Plotting

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

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

Repetition Structures Chapter 9

Step by step set of instructions to accomplish a task or solve a problem

Why use MATLAB? Mathematcal computations. Used a lot for problem solving. Statistical Analysis (e.g., mean, min) Visualisation (1D-3D)

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

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

The Mathematics of Big Data

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

Files and File Management Scripts Logical Operations Conditional Statements

Introduction To MATLAB Introduction to Programming GENG 200

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.

Math Scientific Computing - Matlab Intro and Exercises: Spring 2003

University of Alberta

Getting To Know Matlab

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

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

Short Version of Matlab Manual

Introduction to MATLAB

MATLAB - Lecture # 4

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

EP375 Computational Physics

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

MATLAB TUTORIAL WORKSHEET

Programming in MATLAB

Lecture 2 Introduction to MATLAB. Dr.Tony Cahill

Introduction to Matlab

Quick MATLAB Syntax Guide

Additional Plot Types and Plot Formatting

Introduction to MATLAB Practical 1

MATLAB PROGRAMMING LECTURES. By Sarah Hussein

INTRODUCTION TO NUMERICAL ANALYSIS

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

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

FOR LOOP. for <indexmin:indexstep:indexmax> {statements} end

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Introduction to MATLAB

An Introduction to MATLAB II

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

What is MATLAB? It is a high-level programming language. for numerical computations for symbolic computations for scientific visualizations

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

Short Introduction into MATLAB

Analysis Methods in Atmospheric and Oceanic Science AOSC 652. Introduction to MATLAB. Week 8, Day Oct 2014

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

Introduction to MATLAB for Numerical Analysis and Mathematical Modeling. Selis Önel, PhD

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

A Quick Tutorial on MATLAB. Zeeshan Ali

Getting started with MATLAB

Introduction to GNU-Octave

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Appendix A: MATLAB Basics

Stokes Modelling Workshop

AMS 27L LAB #2 Winter 2009

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

Matlab Input/Output. Goal of this section Learn user-controlled Input Output Read/write data files (optional) Input/output 5-

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

Laboratory 1 Octave Tutorial

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Summer 2009 REU: Introduction to Matlab

2 Amazingly Simple Example Suppose we wanted to represent the following matrix 2 itchy = To enter itchy in Matla

Finding, Starting and Using Matlab

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

Transcription:

Programming Until now we worked with Matlab interactively, executing simple statements line by line, often reentering the same sequences of commands. Alternatively, we can store the Matlab input commands in a file called an M-file, an ordinary ASCII text file with the extension.m, (e.g., myfile.m). M-files can be created using your favorite text editor (emacs, vi) or a built-in Matlab editor. There are two types of M-files: script files and function files. 1. Script files. A script file is an M-file which contains a set of Matlab commands. A script file is executed by typing the name of the file without the.m extension from the Matlab command line. It should be visible to the Matlab environment - by changing the Current directory to the place where the script was saved using the Matlab GUI; or from the command line, check help cd. Example: script which solves quadratic equations. %----- solve quadratic equation ---- % a*x^2+b*x+c=0 % x1,x2=(-b+-sqrt(b^2-4ac))/(2*a) clc; % clear command window a=2; b=-1; c=5; sqd=sqrt(b^2-4*a*c); x1=(-b-sqd)/2/a % no semicolon x2=(-b+sqd)/2/a % to see results Notice, that all variables in the script files are global and accessible from the workspace after the script execution. Thus, never name a script file the same name as a variable it computes! 1

In some cases, it is convenient to enter input data interactively using the input command. Instead of a line a=2; we put a=input( enter a: ); and Matlab will ask to input the number (or expression, which will be evaluated). 2. Function files. A function file is similar to the subroutine in Fortran or function in C. It is also an M-file, but all variable in a function file are local. Consider a function which solves quadratic equations, similar to the script above. The first line in a function file is a function definition which begins with the word function. The name of the function (in this case quad_eq_sol) must be the same as the filename in which the function is defined, without the.m extension. Also the set of comment lines after the function definition is special: they are displayed by the command help quad_eq_sol. The first comment line, called the H1 line, is the line which is scanned by the lookfor command: >> lookfor quad_eq_sol quad_eq_sol Solves quadratic equation The rest of the M-file is the body of the function. 2

H1 line output list function name input list function [x1,x2]=quad_eq_sol(a,b,c) % quad_eq_sol Solves quadratic equation % May, 2001 % simple function example sqd=sqrt(b^2-4*a*c); x1=(-b-sqd)/2/a; x2=(-b+sqd)/2/a; body of the function Now our function can be executed, with the output explicitly specified: >> clear >> a1=1; b1=5; c1=-3; >> [root1,root2]=quad_eq_sol(a1,b1,c1); >> root1,root2 root1 = -5.5414 root2 = 0.5414 Note, the variables that are passed to the function do not need to have the same name as in the function definition. If the output is omitted and there is no semicolon at the end of the call statement, >> quad_eq_sol(a1,b1,c1) 3

ans = -5.5414 the first variable in the output list is displayed. Any function, built-in or user-written, can be executed inside of another function - in the same way we used sqrt to calculate the square root. Matlab allows several functions to be written in a single file. The first function in a such file, the main function, is like a regular function. But all functions, written below the first function, so called subfunctions, are accessible only to the main function, and cannot be called from the outside. 3. Language elements. Matlab, as a programming language, has several standard control-flow constructions to specify the order in which computations are performed. if-elseif-else example: if x<= -3 f=-1; elseif (x>-3) & (x<3) f=0; else f=1; end Six relational operations support if-elseif-else construction: < less than <= less than or equal > greater than >= greater than or equal == equal ~= not equal 4

and for logical: & logical AND logical OR ~ logical complement (NOT) xor exclusive OR. These operations work not only with scalars, but also with vectors and matrices of the same size. For instance, >> u=[1 3 7 9]; v=[0 5 7 8]; >> a1= u > v, a2 = u==v, a3= (u>v)&(u<5) a1 = 1 0 0 1 a2 = 0 0 1 0 a3 = 1 0 0 0 The result is 1 if the relation is true, or 0 where it is false. for loops example: for i=0:5:100 y=x+5*i end The counter of the loop is initial:step:last. Nested loops are allowed. while loops the pattern: while condition --statements-- end The loop will execute a group of statements while the condition is satisfied (true). example: find the sum of all odd numbers less than 100. 5

s=0; i=1; while i<100 s=s+i; i=i+1; end break This command inside for or while loop terminates the execution of the loop without checking any other conditions. In the case of a nested loops, break terminates only the innermost loop. error The command error( some error message ) inside a script or a function aborts the execution and displays the error message. Note, that for or while loops are much slower than operations on vectors and matrices in Matlab. As an example, consider problem 4b from the last Exercises set. We can use the command cputime to get the CPU time in seconds for each method. First, using for loop: t=cputime; n=50000; s=0; for i=1:n s=s+(-1)^(i+1)/i; end; s, cputime-t after running this script we get: s = 0.6931 6

ans = 2.6040 Using vectorized operations: t=cputime; n=50000; repmat([1-1],1,n/2)*(1./(1:n))' cputime-t gives ans = 0.6931 ans = 0.1400 which is ~18 times faster. EXERCISES 1. The sequence of Fibonacci numbers begins with the integers 1123581321,,,,,,,, where each number after the first two is the sum of the two preceding numbers. Write a script/function that displays the vector with first n Fibonacci numbers. 2.Write a script/function to evaluate a) = --- for x = 25, 45, and N = 25, 50, 75, 150 i! e x N i = 0 xi b) e x = ------------ 1, x = 25, 45, and the same values of N as above. N x i --- i! i = 0 7

3. Suppose x=[ -2 0 0 3 6 9] and y=[-6-1 0 4 5 12] Check the result of the following operations: a) u1 = x&y b) u2 = x y c) u3 = x>=y d) u4 = x~=y 4. Input/Output First, we discuss the export/import of the numeric data files. The simplest way to write some data to the file is the command save. For example, to export a small table of the sine function >> x=linspace(0,2*pi,6); y=sin(x); Sine=[x' y'] Sine = 0 0 1.2566 0.9511 2.5133 0.5878 3.7699-0.5878 5.0265-0.9511 6.2832-0.0000 we issue the following command: >> save SineFile.dat Sine -ASCII which creates the file SineFile.dat in the current working directory. To check what is in the file, type more SineFile.dat from the Unix prompt: 0.0000000e+000 0.0000000e+000 1.2566371e+000 9.5105652e-001 2.5132741e+000 5.8778525e-001 8

3.7699112e+000-5.8778525e-001 5.0265482e+000-9.5105652e-001 6.2831853e+000-2.4492936e-016 The -ASCII option specifies 8-digits plain text output instead of a binary (the default). Check help save for more options. If we need to import the data from the file SineFile.dat, we use the command load: >> A=load('SineFile.dat'); A A = 0 0 1.2566 0.9511 2.5133 0.5878 3.7699-0.5878 5.0265-0.9511 6.2832-0.0000 The table of the sine function is represented now by the matrix A. Another useful command which writes formatted data to a file or to the screen is fprintf. Let s write the matrix A above to the file sine2.txt: >> fid1=fopen('sine2.txt','w'); >> fprintf(fid1,'%12.5e %12.5e\n',A'); >> fclose(fid1); These lines need some explanations, as an example of a low-level I/O facilities in Matlab. First, fopen opens a file sine2.txt in the write mode 'w', and assigns the file identifier (similar to the file unit number in Fortran, i.e., write(unit=fid,*) ) to fid1. The fprintf command writes the data to the file identified by fid1. The formatting of the data 9

is based on the rules of the C-language I/O syntax, with some Matlab extensions, which allow, in particular, an explicit output of matrices/ vectors. The string '%12.5e %12.5e\n'reads: two numbers on a line (\n stands for new line), using for each number the floating-point conversion. The minimum field width is 12, and the precision, or number of digits after the decimal point, is 5. Since the format string is recycled through the elements of A columnwise by default, A was transposed. Finally, the last statement closes the file. If is file identifier is omitted (or equal to 1), the output of fprintf goes to the screen. In the next example fprintf displays the table of the sine function on the screen in a Fortran/C style. The following script clc x=linspace(0,2*pi,6); y=sin(x); fprintf(' \n'); fprintf(' x sin(x)\n'); fprintf('------------------------\n'); for i=1:6 fprintf(' %10.5f %10.5f\n',x(i),y(i)); end fprintf('------------------------\n'); prints x sin(x) ------------------------ 0.00000 0.00000 1.25664 0.95106 2.51327 0.58779 3.76991-0.58779 5.02655-0.95106 10

6.28319-0.00000 ------------------------ With fprintf it is also easy to mix numbers with text: >> fprintf('the sine of Pi/4is:\n... sin(%6.4f)=%6.4f\n',pi/4,sin(pi/4)) The sine of Pi/4 is: sin(0.7854)=0.7071 Matlab also provides the disp command, a higher-level command than fprintf. disp is easy to use, but it has limited control over the appearance of the output. In the simplest case, disp displays the contents, but not the name of the array: >> A=reshape(1:6,2,3); disp(a) 1 3 5 2 4 6 or >> x=(1:3), y=(2:4) x = 1 2 3 y = 2 3 4 >> disp([x' y']) 1 2 2 3 3 4 11

The mixed text-numbers output is possible with the disp command, but first we need some information about character strings. In Matlab character strings are entered within two single quotes, and treated as a row vector with one element per character, including spaces. >> line='i"m a string' line = I"m a string >> size(line) ans = 1 12 The row vector with strings as its components concatenates all strings: >> line1=['one' 'two' 'three'] line1 = onetwothree Thus, to mix text with numbers, we should first transform numbers to strings, which is accomplished by the function num2str: >> disp(['pi = ' num2str(pi)]) Pi = 3.1416 >> num2str(pi,12) % to get 12 digits ans = 3.14159265359 >> x=1:3; disp(['x-vector: ' num2str(x)]) x-vector: 1 2 3 but to display a column vector: 12

>> y=(2:4)'; disp('y='); disp(y); %!with ; y= 2 3 4 The disp-version of the script which prints the sine function table: clc x=linspace(0,2*pi,6); y=sin(x); disp(' '); disp(' x sin(x)'); disp('------------------------'); for i=1:6 disp([' ' num2str(x(i)) ' '... num2str(y(i)) ]); end disp('------------------------'); which produces x sin(x) ------------------------ 0 0 1.2566 0.95106 2.5133 0.58779 3.7699-0.58779 5.0265-0.95106 6.2832-2.4493e-016 ------------------------ 13

It is not as good as with fprint. 5. 2D Plots. Matlab has powerful tools for visualization which include high-level 2D and 3D color graphics and animation functions. plot is the most useful command for producing simple 2D plots. The general pattern of the command is plot(xvalues,yvalues, style-options ), where style-options is a character string made from one element from any or all the following 3 columns: y yellow. point - solid m magenta o circle : dotted c cyan x x-mark -. dashdot r red + plus -- dashed g green * star b blue s square w white d diamond k black v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram The following script illustrates several elements of the Matlab plotting environment: 14

% script plots sums of Taylor series terms of % sin(x) % % sin(x)=x-x^3/3!+x^5/5!-... % clf x=linspace(0,2*pi,100); ysin=sin(x); y1=x; y3=x-x.^3/6+x.^5/120; plot(x,ysin,x,y1,'--',x,y3,'o') axis([0 5-1 5]) xlabel('x') ylabel('y=sin(x)') title('series approximations of sin(x)') text(3.5,0,'sin(x)') text(2.5,3,'x') text(2.8,1.5,'x-x^3/6+x^5/120') 15