Anda di halaman 1dari 33

Math 251 Fall 2011-2012

Matlab

is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. performance language for technical computing. High level matrix/array language

High

Integrates:

Computations Programming Graphics

Has

a family of toolboxes.
3

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. When you back up to a previous command that you want to use, hit Enter and it will execute. You can also edit it when you get to it (use the left and right arrows , and modify the command), then execute it.

The

workspace is used to view program variables

Note: You may sometimes have the current directory instead of the workspace where you can find all the files contained in the indicated path.
The

Command History contains all the previous commands

Note: You can delete some of the non important commands in the command history or clear the entire command history by right clicking on the commands in the command history
6

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 "clean screen. the command Window only, giving a
7

pi:

= 3.1415926

eps: =2.2204e-016 (smallest amount by which 2 numbers can 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 which was not assigned to another variable. ) If you create a variable with the same name of a built-in variable then you cannot refer to the built in variable unless you delete the variable that you created.

digits by default, but always stores numbers and computes to the equivalent of 16 decimal digits (IEEE double precision).
(However, one can convert to single precision: single(pi) returns 3.141593)

Format: MATLAB displays floating point numbers to 5 decimal

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 to
the 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! fix(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 b
9

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 string


Often 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).
num2str(pi,9) returns 3.14159265 Ex:

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.
>> s = sprintf('%+.5f',pi); >> s = sprintf('%+.5e',pi); >> s = sprintf('%+.5g',7.34000000); >> s = sprintf('%+.5f\n',[pi,exp(1),sqrt(2)]); Ex: >> disp(s) returns: +3.14159

>> disp(s) returns: +3.14159e+00 >> disp(s) returns: +7.34 >> disp(s) returns: +3.14159 +2.71828 +1.41421
10

Arithmetic:

+-*/^

Element-by-element operations on vectors: + - .* ./ .^ ==, >=, >, <=, <, ~=


(~ means not)

Relational:

Logical:

& and, | or
11

A vector v is defined using the brackets. To define a row vector:


Open

the brackets Write inside the brackets the elements of the vector separate 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

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

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 i to 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

x([i j]) = x([j i]) : permutes the ith and jth components of a row vector x. x = [x 3]: adds one element 3 at the end of a row vector. x = [10 x]: adds one element 10 at the beginning of a row vector. z = [x y] : generates a new row vector z by concatenating the elements of 2 row vectors x and y.

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


15

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 in the vector x and its position.
i.e. returns i such that x(i) = Maxvalue

N.B.:

Similarly, min(x) returns the smallest element in the vector x and its position.
16

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 the indices of those satisfying the logical expression. Example: a=[10,20,30,0,40,0,2,45] b=find(a) returns: b=1 b=find(a==10) returns: b=1 b=find(a>10) returns: b=2 b=find(a>10 & a<40) returns: b = 2

2 3

3 5

5 8

17

If: if expression sequence of statements elseif expression sequence of statements else sequence of statements end

18

For: for i = start range : increment : end range sequence of commands end

While: while condition sequence of commands end

19

break : allows to exit early from the for or while loop in which it appears and to pass control 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 the program completely, which causes an immediate return from the m.file.

20

Example1:

% get the sum S=1+2++100 n = 100; S=0; for i=1:n S=S+i; end S % or n=input('n= '); % Initialize S

21

Example2:

% get the smallest integer n such that S=1+2++n > 1000 n = 0; S = 0; while S<1000 n=n+1; S=S+n; end n,S % Initialize n % Initialize S

equivalently:

S = 0; for n=1:1000 S=S+n; if S>1000 break end end n,S

% Initialize S % 1000 is a loose upper bound for n

22

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

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


Keyword function Output Argument(s) Function Name (same as file name .m) input Argument(s)

function y = mean(x) % Description of your code m = length(x); y = sum(x)/m;


output_value = mean(input_value) Command Line Syntax

24

Open an m-file and write the following function:


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

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

25

Example1 (revisited): tic S=0; for i=1:n S=S+i; end toc

% get the sum S(n) = 1+2++n

function S = mySum(n)

Remark: tic and toc functions tic (operations) toc % measures the elapsed time
Experiment the tic-toc functions on the above example, when evaluating: mySum(100), mySum(106), mySum(1020),
26

% saves the current time

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

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

Using the previous two functions:

p( y) = 2 y + 3 y + y + 5 Let: Evaluate p(1) and p(1/3) in two ways, by calling the previous functions.
4 3

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

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 defined directly in the command window, without an m.file.
2.

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


30

Plotting two-dimensional Curves: plot (x,y, plotting options) generates a linear plot of the values 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, with p specifying the current plot as the p-th window.
31

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)on the current axes, where (x,y) is in units from the current plot. legend (string1, string2,) used to distinguish 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

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)
33

Anda mungkin juga menyukai