introduction to matlab - memorial university of … to matlab what is matlab? matlab is a commercial...

41
Eng. 4061 Marine Production Management Introduction to Matlab

Upload: hoangtuyen

Post on 13-Apr-2018

249 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Eng. 4061 Marine Production Management

Introduction to Matlab

Page 2: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What is Matlab?

Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. Matlab is available for PC's, Macintosh and UNIX systems.Matlab is well adapted to numerical experiments.

Matlab program and script files (m-files) always have filenames ending with ".m"; The programming language is exceptionally straightforward since almost every data object is assumed to be an array. Graphical output (figure) is available to supplement numerical results.

Online help is available from the Matlab prompt (a double arrow) by typing help.

Page 3: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What kind of graphics are possible in Matlab?

Polar plot: t=0:.01:2*pi; polar(t,abs(sin(2*t).*cos(2*t))); Line plot:

x=0:0.05:5;,y=sin(x.^2);,plot(x,y);

Stem plot: x = 0:0.1:4;, y = sin(x.^2).*exp(-x); stem(x,y)

Page 4: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What kind of graphics is possible in Matlab?

Mesh plot:z=peaks(25);, mesh(z);

Surface plot: z=peaks(25);, surf(z);, colormap(jet);

Contour plot: z=peaks(25);,contour(z,16); Quiver plot:

Page 5: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Using Help in Matlab

Online help is available from the Matlab prompt (>> a double arrow), both generally (listing of all available commands):

>> help[a long list of help topics follows]

and for specific commands:

>> help fft

[a help message on the fft function follows].

Page 6: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What is Matlab? MATLAB consists of:

The MATLAB language a high-level matrix/array language with control flow statements,

functions, data structures, input/output, and object-oriented programming features.

The MATLAB working environment the set of tools and facilities that you work with as the MATLAB user or

programmer, including tools for developing, managing, debugging, and profiling

Handle Graphics the MATLAB graphics system. It includes high-level commands for two-

dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics.

…(cont’d)

Page 7: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What is Matlab? The MATLAB function library. a vast collection of computational algorithms ranging from

elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms as well as special image processing related functions

The MATLAB Application Program Interface (API) a library that allows you to write C and Fortran programs

that interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

Page 8: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What is Matlab? Some facts for a first impression

Everything in MATLAB is a matrix !

MATLAB is an interpreted language, no compilation needed (but possible)

MATLAB does not need any variable declarations, no dimension statements, has no packaging, no storage allocation, no pointers

Programs can be run step by step, with full access to all variables, functions etc.

Page 9: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What does matlab code look like? t = 0:pi/100:2*pi; y = sin(t); plot(t,y)

Page 10: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

What does matlab code look like?

Remember:

EVERYTHING IN MATLAB IS A MATRIX !

creates 1 x 200 Matrix

Argument and result: 1 x 200 Matrix

t = 0:pi/100:2*pi; y = sin(t); plot(t,y)

Page 11: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment
Page 12: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Rows and columns are always numbered starting at 1

A single number is really a 1 x 1 matrix in Matlab!

Matlab variables are not given a type, and do not need to be declared

Any matrix can be assigned to any variable

Page 13: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Building matrices with [ ]:

A = [2 7 4]

A = [2; 7; 4]

A = [2 7 4; 3 8 9]

B = [ A A ]

2 7 4

274

2 7 43 8 9

2 7 43 8 9

2 7 43 8 9

Page 14: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment
Page 15: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

A matrix can be indexed using another matrix, to produce a subset of its elements:

a = [100 200 300 400 500 600 700] b = [3 5 6]

c = a(b):

300 500 600

Page 16: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Matrices a vectorx = [1 2 5 1]

x = 1 2 5 1

a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x = 1 2 3 5 1 4 3 2 -1

Page 17: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Matrices x(i,j) subscription

whole row

whole column

y=x(2,3)y = 4

y=x(3,:)y = 3 2 -1

y=x(:,2)y = 2 1 2

Page 18: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Operators (arithmetic)

+addition- subtraction* multiplication/ division^power‘ complex

conjugate transpose

.* element-by-element mult

./ element-by-element div

.^ element-by-element power

.‘ transpose

Page 19: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Operators (relational, logical)

== equal~= not equal< less than<= less than or equal> greater than>= greater than or equal

& AND| OR~ NOT

1−

pi 3.14159265…j imaginary unit, i same as j

Page 20: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Generating Vectors from functions zeros(M,N) MxN matrix of zeros

ones(M,N) MxN matrix of ones

rand(M,N) MxN matrix of uniformly distributed random numbers

on (0,1)

x = zeros(1,3)x =

0 0 0

x = ones(1,3)x =

1 1 1

x = rand(1,3)x = 0.9501 0.2311 0.6068

Page 21: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Programming in Matlab (M-files) Executing commands in the command window is

fine for short scripts; but when dealing with long scripts for complex problem-solving (or when programming) M-files is a must.

It allows the user to write MATLAB command in a text file (called M-file) and then MATLAB will open the file and execute the commands exactly as it would if the user typed them at the MATLAB Command Window. The M-file editor is the MATLAB’s tool for creating M-files.

Page 22: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Programming in Matlab (M-files) There are two basic kinds of m-files:

Scripts Functions

Scripts are m-files that execute a series of statements

Functions are m-files that accept arguments and produce an output

Page 23: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Example Script 1 Find the solution, x, to the following system

of equations

Page 24: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Example Script 1: solution Use the MATLAB editor to create a new file Enter the following statement:A = [1 2 3; 3 3 4; 2 3 3];b = [1; 1; 2];x = A\b

Page 25: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Example Script 2 Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x) y3 = 0.5cos(x)

in the interval: 0x2

Page 26: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Example Script 2: solution Use the MATLAB editor to create a new file Enter the following statement:x = 0:pi/100:2*pi;

y1 = 2*cos(x);

y2 = cos(x);

y3 = 0.5*cos(x);

plot(x,y1,'--',x,y2,'-',x,y3,':')

xlabel('0 \leq x \leq 2\pi')

ylabel('Cosine functions')

legend('2*cos(x)','cos(x)','0.5*cos(x)')

title('Typical example of multiple plots')

axis([0 2*pi -3 3])

Page 27: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Script shortcomings All variables created in a script file are

added to the workspace. This may be undesirable because: Variables already existing in the workspace may

be overwritten. The execution of the script can be affected by

the state variables in the workspace.

Use a function for anything complicated

Page 28: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

The Anatomy of a Function

function f = factorial(n) (1) % FACTORIAL(N) returns the factorial of N. (2) % Compute a factorial value. (3) f = prod(1:n); (4)

Page 29: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Differences between Scripts and Functions

Page 30: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Functions: input & output arguments input arguments are listed inside

parentheses following the function name. The output arguments are listed inside the

brackets on the left side. They are used to transfer the output from the function file.

The general form looks like this

function [outputs] = function_name(inputs)

Page 31: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Functions: input & output arguments Examples of input and output arguments

function area=TrapArea(a,b,h) Three inputs and one output

function [h,d]=motion(v,angle) Two inputs and two outputs

Page 32: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Inputs to scripts?

Inputs are sent to script files by: Defining the variable in the script itself Defining the variable in the workspace Defining the variable when the script

executes

Page 33: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Inputs to scripts?

We've discussed the first two, so lets look at Defining the variable when the script

executes

This means that we will ask the user to supply some information when the script is executed Using the input command

Page 34: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

The Input CommandLets try an example script% This script file calculates the average of points

% scored in three games.

% The point from each game are assigned to a variable

% by using the `input' command.

game1 = input('Enter the points scored in the first game ');

game2 = input('Enter the points scored in the second game ');

game3 = input('Enter the points scored in the third game ');

average = (game1+game2+game3)/3

Page 35: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Flow Control The most common decision-making (or flow

control) structures in matlab are: The if ... else ... end structure Example, based on quadratic formula:discr = b*b - 4*a*c;

if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');

elseif discr == 0

disp('Discriminant is zero, roots are repeated')

else

disp('Roots are real')

end

Page 36: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Flow Control Logical operators are used to compare two

objects:

Page 37: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Flow Control Another common flow control structure is: The for ... end loop Example:for ii=1:5

x=ii*ii

end

Page 38: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Flow Control Can also use nested loops as well. To populate a 5x5 symmetric matrix where

the indices correspond to i/j we have:n = 5; A = eye(n);

for j=2:n

for i=1:j-1A(i,j)=i/j;A(j,i)=i/j;

end

end

Page 39: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Saving output to a file The command fprintf is used to write

output to a file.To save the results of some computation to a

file in a text format requires the followingsteps:1. Open a file using fopen2. Write the output using fprintf3. Close the file using fclose

Page 40: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Saving output to a file

% write some variable length strings to a file:

op = fopen('weekdays.txt','wt');

fprintf(op,'Sunday\nMonday\nTuesday\nWednesday\n');

fprintf(op,'Thursday\nFriday\nSaturday\n');

fclose(op);

Notes: the option 'wt' is used in the windows platform to set a

file for writing. the command \n forces a carriage return

Page 41: Introduction to Matlab - Memorial University of … to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment

Furthering your matlab skills The scripts presented in this lecture are

merely an introduction to matlab that barely scrape the surface

To understand it yourself you must really get your hands dirty and dig into programming.

The built-in help is very good in matlab, so if you are unsure of how to do something you should check there first