matlab-fall 11-12 introduction to matlab part i

33
Math 251 Fall 2011-2012 1

Upload: husam-qutteina

Post on 06-Apr-2018

232 views

Category:

Documents


1 download

TRANSCRIPT

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 1/33

Math 251

Fall 2011-2012

1

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 2/33

 

2

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 3/33

Matlab is a commercial "Matrix Laboratory"package which operates as an interactiveprogramming environment.

High performance language for technical

computing. High level matrix/array language

Integrates: Computations

Programming Graphics

Has a family of toolboxes.

3

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 4/33

4

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 5/33

Used to type commands: run a Matlab code

Use as a calculator by typing commands at the prompt >>

Note:

The up-arrow key will display previous commands. Whenyou back up to a previous command that you want to use,hit Enter and it will execute. You can also edit it when youget to it (use the left and right arrows , andmodify the command), then execute it.

5

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 6/33

The workspace is used to view programvariables

Note:

You may sometimes have the current directory  instead of 

the workspace where you can find all the files contained inthe indicated path.

The Command History contains all the

previous commandsNote:

You can delete some of the non important commands inthe command history or clear the entire command historyby right clicking on the commands in the command history

6

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 7/33

Variables in Matlab are not declared but they are directly

assigned Assignment statement : Variable = number (or expression)

num = 6; % assignment only

num = 6 % assignment & display

Variable names:

Must start with a letter

May contain letters, digits and underscore

Matlab is case sensitive

Clear all: command removing all variables, functions, … from

memory, leaving the workspace empty.

clc: Command clearing the command Window only, giving a

"clean screen.”

7

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 8/33

pi: = 3.1415926…………

eps: =2.2204e-016 (smallest amount by which 2 numberscan differ)

Inf or inf : , infinity

NaN or nan: not-a-number

(results from operations which have undefined numerical results)

ans (The variable ans will keep track of the last output whichwas not assigned to another variable. ) 

If you create a variable with the same name of a built-invariable then you cannot refer to the built in variable unlessyou delete the variable that you created. 

8

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 9/33

  Format: MATLAB displays floating point numbers to 5 decimal

digits by default, but always stores numbers and computes to theequivalent of 16 decimal digits (IEEE double precision).

(However, one can convert to single precision: single(pi) returns 3.141593)

The output format can be changed using the format command.

Examples of format types:

format short  (fixed point format, with 4 digits after the decimal point, rounding tothe closest),

format long (fixed point format, with 15 digits after the decimal point)

format short e, format long e (same as above but in floating point format)

format short g, format long g (best of fixed or floating point format)

factorial(n): returns the value of n! 

f ix(x): returns the integral part of x

fix(D/d): returns the integral part of the quotient of the division of 

D by d.

rem(a,b): returns the remainder of the division of a by b9

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 10/33

disp(‘…’): displays the content of the quotations

disp(X) displays the variable X, without printing its name.

Another way to display X is to type its name, but this prints a leading “X=“.

num2str(X): converts number X to stringOften used for displaying variables and strings, together. However, the two resulting

strings should first be concatenated.

Ex: x = 35; disp([‘Your lucky number is : ',num2str(x)])

num2str(X,precision) : the precision argument specifies the number of digits the output string is to contain (the default is five).

Ex: num2str(pi,9)  returns 3.14159265

num2str(X,format) : converts X, using a given format.

(formats are similar to those used in sprintf: see the example below)

sprintf(format,X) : converts the data in X into a string and controls the

precision and the notation of the output.Ex: >> s = sprintf('%+.5f ',pi); >> disp(s) returns: +3.14159

>> s = sprintf('%+.5e',pi); >> disp(s) returns: +3.14159e+00

>> s = sprintf('%+.5g',7.34000000); >> disp(s) returns: +7.34

>> s = sprintf('%+.5f\n',[pi,exp(1),sqrt(2)]);  >> disp(s) returns: +3.14159

+2.71828

+1.41421

10

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 11/33

Arithmetic: + - * / ^

Element-by-element operations on vectors:

+ - .* ./ .^

Relational: ==, >=, >, <=, <, ~=

(~ means ‘not’)

Logical: & and, | or

11

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 12/33

A vector v is defined using the brackets.

To define a row vector:

Open the brackets

Write inside the brackets the elements of the vectorseparate them using EMPTY SPACE or a COMMA

Example: v =[1 2 5 4] 

To define a column vector:

Open the brackets

Write inside the brackets the elements of the vector

separate them using SEMICOLON. 

Example: v =[1;2;5;4] 

12

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 13/33

x=a:c – generates a row vector x, where: The first element is ‘a’

The last element is ‘c’

The difference between any 2 consecutive values is 1

x=a:b:c – generates a row vector x, where: The first element is ‘a’

The last element is ‘c’

The difference between any 2 consecutive values is ‘b’

13

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 14/33

 

MATLAB index starts at 1,i.e. the first entry of the vector x is accessed by writing x(1) and not x(0)

x(i): returns the ith element of the vector x.

x(i:j): returns the elements of vector x from index ito index j.

x(end): returns the last element of x

length(x): returns the # of elements in x

sort(x) : returns a vector whose components are

those of x sorted from the smallest to the greatest.

y’ :returns the transpose of y.

14

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 15/33

x([i j]) = x([j i]) : permutes the ith and jth componentsof a row vector x.

x = [x 3]: adds one element ‘3’ at the end of a rowvector.

x = [10 x]: adds one element ‘10’ at the beginning of a row vector.

z = [x y] : generates a new row vector z byconcatenating the elements of 2 row vectors x and y.

N.B.: the same syntax is used on column vectors, by

adding “;” adequately.

15

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 16/33

sum(x): returns the sum of the elements of the vector x.

prod(x): returns the product of the elements of the vector x.

diff (x) : returns the vector

[x(2)-x(1), x(3)-x(2), …, x(n)-x(n-1)].

If length(x) = n, then length(diff(x)) = n-1. 

Maxvalue = max(x): returns the greatest element in the

vector x.

[Maxvalue pos] = max(x): returns the greatest element inthe vector x and its position.

i.e. returns i such that x(i) = Maxvalue

N.B.: Similarly, min(x) returns the smallest element in thevector x and its position.

16

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 17/33

 Ind = find(X) returns the indices of all nonzero elements of 

the vector X.

Ind = find (logical expression on X) - evaluates the logical

expression on the elements of the array X and returns theindices of those satisfying the logical expression.

Example: a=[10,20,30,0,40,0,2,45]

b=find(a) returns: b = 1 2 3 5 7 8

b=find(a==10) returns: b = 1

b=find(a>10) returns: b = 2 3 5 8

b=find(a>10 & a<40) returns: b = 2

17

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 18/33

If:

if  expression

sequence of statements

elseif  expressionsequence of statements

else

sequence of statements

end

18

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 19/33

For:for i = start range : increment : end range

sequence of commands 

end

While:

while condition

sequence of commandsend

19

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 20/33

 

break  :  allows to exit early from the “for” or“while” loop in which it appears and to passcontrol to the first statement after the end of 

that loop.N.B.: break is not defined outside a “for” or “while” loop

return:  allows to stop the execution of theprogram completely, which causes an immediatereturn from the m.file.

20

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 21/33

Example1:  % get the sum S=1+2+…+100

n = 100; % or n=input('n= ');

S=0; % Initialize S

for i=1:n

S=S+i;

end

S

21

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 22/33

Example2:  % get the smallest integer n such that S=1+2+…+n > 1000

n = 0; % Initialize n 

S = 0; % Initialize S

while S<1000

n=n+1;

S=S+n;

end

n,S

equivalently: S = 0; % Initialize S

for n=1:1000 % 1000 is a loose upper bound for n 

S=S+n;

if S>1000break

end

end

n,S

22

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 23/33

Files containing a code are m.files.

m.files are created using a text editor

File → new → m.file

Two kinds of m.files:

Scripts: sequence of commands

Functions: with input and output arguments

m.files are used as any other MATLAB function or

command

23

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 24/33

  In order to write a function you need first to create anew m-file:

Keyword function Function Name (same as file name .m) 

Output Argument(s)  input Argument(s)

»output_value = mean(input_value) Command Line Syntax

function y = mean(x)

% Description of your code

m = length(x);

y = sum(x)/m;

24

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 25/33

Open an m-file and write the following function:

On the command window we run the function:

[c d] = myaddProd(3,6)

Matlab returns c =9 and d = 18

Note: For multiple output arguments include them between

brackets and separate them by a comma

For multiple input arguments include them between

parentheses and separate them by a comma

function [mysum, myprod] = myaddProd(inp1,inp2)

mysum = inp1 + inp2;

myprod = inp1 * inp2;

25

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 26/33

Example1 (revisited): % get the sum S(n) = 1+2+…+n

function S = mySum(n)

tic

S=0;

for i=1:n

S=S+i;end

toc

Remark: tic and toc functions

tic % saves the current time

…(operations)

toc % measures the elapsed time

Experiment the tic-toc functions on the above example, when evaluating:

mySum(100), mySum(106), mySum(1020),…

26

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 27/33

Example 3:  % polynomial evaluation (1)

function p = EvaluatePolyStraight(a,y)

% Input a vector a = [a(1),a(2),...,a(n+1)]

% Input a real number y% Output the value of p(y) = a(n+1)*y^n + ... + a(2)*y + a(1)

n = length(a) - 1;

p = a(1);

t = y;for i=2:n+1

p = p + a(i)*t;

t = t*y;

end

27

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 28/33

Example 4:  % polynomial evaluation (2)

function p = EvaluatePolyNested(a,y)

% Input a = [a(1),a(2),...,a(n+1)] and y% Output Value of p(y) = a(n+1)*y^n + ... + a(2)*y + a(1)

n = length(a) - 1;

p = a(n+1);for i=n:-1:1

p = p*y + a(i);

end

28

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 29/33

Using the previous two functions:

Let:

Evaluate p(1) and p(1/3) in two ways, by calling the

previous functions.

A = EvaluatePolyStraight([5,1,0,3,2],1)

B = EvaluatePolyStraight([5,1,0,3,2],1/3)

or

A = EvaluatePolyNested([5,1,0,3,2],1)

B = EvaluatePolyNested([5,1,0,3,2],1/3)

29

532)(34

+++= y y y y p

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 30/33

One may define a function “f” using the function_handle (@):

f  = @(name of variables)(expression)Examples:

  >> f = @(x)(x^2-2*x-1);

>> f(1) returns -2;

>>g=@(x,y)(x^2+y^2-2*x-1);

>>g(0,1) returns 0;

Remarks:

1. When using the function handle, a function can be defineddirectly in the command window, without an m.file.

2. A function handle, can be passed in as an input-argument to

another function.

30

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 31/33

Plotting two-dimensional Curves:

plot (x,y, ‘plotting options’) – generates a linear plot of thevalues of x (horizontal axis) and y (vertical axis).

Note: The plotting options can be the color of the plot, its shape,the line width, its style…

Plotting three-dimensional Curves:

plot3 (x,y,z, ‘plotting options’) – generates a linear plot of the values of (x,y,z)

z is the vertical axis (default)

→Many tools are available: rotate 3D, …

Other: area graphs, surfaces, bar and scatter graphs,…

subplot (m, n, p) – creates an m by n grid of windows, withp specifying the current plot as the p-th window.

31

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 32/33

Can add to a graph: title (‘text’) -labels top of plot with text in quotes xlabel (‘text’) -labels horizontal x-axis with text in

quotes ylabel (‘text’) -labels vertical y-axis with text in

quotes

text (x,y, ‘text’)-Adds text in quotes to location (x,y)onthe current axes, where (x,y) is in units from the currentplot.

legend (‘string1’, ‘string2’,…) – used todistinguish between plots on the same graph

Adding new curves to the existing graph: hold on – retain existing axes, add new curves to current

axes. hold off – release the current figure window for new

plots

32

8/3/2019 MATLAB-Fall 11-12 Introduction to MATLAB Part I

http://slidepdf.com/reader/full/matlab-fall-11-12-introduction-to-matlab-part-i 33/33

x = -pi:pi/10:pi; plot(x,sin(x))

For giving line specifications:

plot(x,sin(x),'--r*','LineWidth',2)

One can add:

title('Sine function')

xlabel('x')

ylabel('sin x')

grid on

Or superpose:

hold on

plot(x,cos(x),'--b*','LineWidth',2)