Anda di halaman 1dari 135

MATLAB Overview

MATLAB Overview
What is MATLAB?

History of MATLAB
Who developed MATLAB Why MATLAB was developed Who currently maintains MATLAB

Strengths of MATLAB Weaknesses of MATLAB


9/8/2013 2

MATLAB Overview
What is MATLAB?

MATLAB
MATrix LABoratory Interactive system Programming language

9/8/2013

MATLAB Overview
What is MATLAB (cont..2)

Considering MATLAB at home


Standard edition
Available for roughly 2 thousand dollars

Student edition
Available for roughly 1 hundred dollars. Some limitations, such as the allowable size of a matrix

9/8/2013

MATLAB Overview
History of MATLAB

Ancestral software to MATLAB


Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems Developed primarily by Cleve Moler in the 1970s

9/8/2013

MATLAB Overview
History of MATLAB, (cont..2)

Later, when teaching courses in mathematics, Moler wanted his students to be able to use LINPACK and EISPACK without requiring knowledge of Fortran MATLAB developed as an interactive system to access LINPACK and EISPACK

9/8/2013

MATLAB Overview
History of MATLAB, (cont..3)

MATLAB gained popularity primarily through word of mouth because it was not officially distributed In the 1980s, MATLAB was rewritten in C with more functionality (such as plotting routines)

9/8/2013

MATLAB Overview
History of MATLAB, (cont..4)

The Mathworks, Inc. was created in 1984 The Mathworks is now responsible for development, sale, and support for MATLAB The Mathworks is located in Natick, MA The Mathworks is an employer that hires coops through our co-op program
9/8/2013 8

MATLAB Overview
Strengths of MATLAB

MATLAB is relatively easy to learn MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix Although primarily procedural, MATLAB does have some object-oriented elements
9/8/2013 9

MATLAB Overview
Weaknesses of MATLAB

MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text)
9/8/2013 10

MATLAB Overview
General Info
Workspace

Command Window

Command History
9/8/2013 11

MATLAB Overview
General Info (cont..2)
The Command Window is where you type in your code, and where Matlab posts solutions (Unless you tell it to do otherwise). The Command History lists all commands typed in to the Command window in case you want to access them again. Note: Previous code can be re-run by hitting the up arrow or double clicking on the code in the command history window The Workspace lists all variables you have created in Matlab, as well as giving the size, number of bytes and type. Another method of viewing current variables is to type the command whos in the command window.
9/8/2013 12

MATLAB Overview
Matlab workspace, working directory & toolbar
Variables are stored in the workspace
who list current variables whos detailed list of variables clear removes all variables from the workspace

Matlab files must be in either the working directory or in a directory listed in the search path
pwd displays the current working directory what lists Matlab specific files in the working directory cd change current working directory path displays the current search path

Workspace Browser
9/8/2013

Path Browser

Simulink

Help Window
13

MATLAB Basics

MATLAB BASICS
For help
If you need additional help in Matlab, at any time you can either click on the question mark at the top of the program, or type >> help function Where function can be whatever function Matlab has a help file for. For example: >> help plot Gives you info on how to use the plot function as well as making it look they way you want it to.
9/8/2013 15

MATLAB BASICS
Saving Data
When using MATLAB, you may wish to leave the program but save the vectors and matrices you have defined. To save the file to the working directory, type save filename where "filename" is a name of your choice. To retrieve the data later, type load filename

9/8/2013

16

MATLAB BASICS
Loading files
There are two main ways to load files into Matlab. 1. Using the load command. For example: >>load data.txt will load a file labeled data.txt into the workspace. To use this method, the file must either be in the current directory listed at the top of the program, or you can add the path of the file so that Matlab knows where to look for it. This function is: >>Addpath('D:\'); Using the location of your file in place of D:\. 2. Using the Import Wizard found under File-Import Data. This method allows you to see what it is you are importing. The variable created in Matlab will be of the same size as the original text or dat file, so if you started with two columns in the text file, you would end up with a matrix of two columns in Matlab.

9/8/2013

17

MATLAB BASICS
Basic Commands
To set a letter to a specific number, use an equal sign such as >>A=5 This will not only set A equal to the number 5, but will also write it out for you. If you do not care to see the output of a command, put a semicolon after it.

9/8/2013

18

MATLAB BASICS
Clearing the Workspace
The function >>clear; Clears out all items in the workspace. This is useful if you want to delete items, or just one item using >>clear A;

9/8/2013

19

MATLAB BASICS
Inserting Comments
You may at times want to use comments in your code to remind yourself or others what you were trying to do. This is done with a %,which comments out and text afterwards. For example:

9/8/2013

20

MATLAB BASICS
Using the colon operator
You can create a single row (or for that matter a single column) using the colon operator. This is very important and useful feature of Matlab as will be seen. For example, if you wanted to create a single row matrix with five numbers in it, you could use the command: >>1:5 Which would give you the output 1 2 3 4 5 Notice that it automatically goes by integers. If you wanted it to go from one to five by 0.2 increments, you could use the command: >>1:0.2:5 Which would give the output 1 1.2 1.4 1.6 1.8 2 and on till 5. If you wanted to set this equal to a variable, such as A, you would then be able to access any number of the sequence you wanted using the commands: >>A=1:0.2:5 >>B=A(3) Which would set your new variable B to the third instance of the row vector A, giving an output of B=1.4
9/8/2013 21

MATLAB BASICS
Variables and Arrays Array: A collection of data values organized into rows
and columns, and known by a single name.
Row 1 Row 2 Row 3 arr(3,2) Row 4

Col 1 Col 2 Col 3 Col 4 Col 5


9/8/2013 22

MATLAB BASICS
Arrays The fundamental unit of data in MATLAB

Scalars are also treated as arrays by MATLAB (1 row and 1 column).


Row and column indices of an array start from 1. Arrays can be classified as vectors and matrices.

9/8/2013

23

MATLAB BASICS
Vector: Array with one dimension Matrix: Array with more than one dimension Size of an array is specified by the number of rows and the number of columns, with the number of rows mentioned first (For example: n x m array).

Total number of elements in an array is the product of the number of rows and the number of columns.

9/8/2013

24

MATLAB BASICS
1 2 a= 3 4 5 6 b=[1 2 3 4] 1 c= 3 5 a(2,1)=3
Row #
9/8/2013

3x2 matrix 6 elements 1x4 array 4 elements, row vector 3x1 array 3 elements, column vector

b(3)=3

c(2)=3

Column #
25

MATLAB BASICS
Variables
A region of memory containing an array, which is known by a user-specified name. Contents can be used or modified at any time. Variable names must begin with a letter, followed by any combination of letters, numbers and the underscore (_) character. Only the first 31 characters are significant. The MATLAB language is Case Sensitive. NAME, name and Name are all different variables.

Give meaningful (descriptive and easy-to-remember) names for the variables. Never define a variable with the same name as a MATLAB function or command.
9/8/2013 26

MATLAB BASICS
Common types of MATLAB variables
double: 64-bit double-precision floating-point numbers They can hold real, imaginary or complex numbers in the range from 10-308 to 10308 with 15 or 16 decimal digits. >> var = 1 + i ; char: 16-bit values, each representing a single character The char arrays are used to hold character strings. >> comment = This is a character string ; The type of data assigned to a variable determines the type of variable that is created.
9/8/2013 27

MATLAB BASICS
Initializing Variables in Assignment Statements An assignment statement has the general form var = expression Examples:
>> var = 40 * i; >> var2 = var / 5; >> array = [1 2 3 4]; >> x = 1; y = 2; >> a = [3.4]; >> b = [1.0 2.0 3.0 4.0]; >> c = [1.0; 2.0; 3.0]; >> d = [1, 2, 3; 4, 5, 6]; >> e = [1, 2, 3 4, 5, 6];
9/8/2013

>> a2 = [0 1+8]; >> b2 = [a2(2) 7 a]; >> c2(2,3) = 5; >> d2 = [1 2]; >> d2(4) = 4;

; semicolon suppresses the automatic echoing of values but it slows down the execution.
28

MATLAB BASICS
Initializing Variables in Assignment Statements Arrays are constructed using brackets and semicolons. All of the elements of an array are listed in row order.

The values in each row are listed from left to right and they are separated by blank spaces or commas.
The rows are separated by semicolons or new lines.

The number of elements in every row of an array must be the same.


The expressions used to initialize arrays can include algebraic operations and all or portions of previously defined arrays.
9/8/2013 29

MATLAB BASICS
Initializing with Shortcut Expressions first: increment: last
Colon operator: a shortcut notation used to initialize arrays with thousands of elements >> x = 1 : 2 : 10; >> angles = (0.01 : 0.01 : 1) * pi; Transpose operator: () swaps the rows and columns of an array 1 1

>> f = [1:4]; >> g = 1:4; >> h = [ g g ];

2 2 h= 3 3 4 4
30

9/8/2013

MATLAB BASICS
Initializing with Built-in Functions
zeros(n) zeros(n,m) zeros(size(arr)) ones(n) ones(n,m) ones(size(arr)) eye(n) eye(n,m) >> a = zeros(2); >> b = zeros(2, 3); >> c = [1, 2; 3, 4]; >> d = zeros(size(c));

length(arr) size(arr)
9/8/2013 31

MATLAB BASICS
Initializing with Keyboard Input
The input function displays a prompt string in the Command Window and then waits for the user to respond. my_val = input( Enter an input value: ); in1 = input( Enter data: ); in2 = input( Enter data: ,`s`);

9/8/2013

32

MATLAB BASICS
Multidimensional Arrays
A two dimensional array with m rows and n columns will occupy mxn successive locations in the computer s memory. MATLAB always allocates array elements in column major order. a= [1 2 3; 4 5 6; 7 8 9; 10 11 12]; a(5) = a(1,2) = 2 A 2x3x2 array of three dimensions
1

4
1 4 7 2 5 8 3 6 9 7 10

c(:, :, 1) = [1 2 3; 4 5 6 ]; c(:, :, 2) = [7 8 9; 10 11 12];


9/8/2013

2
5 8 11
33

10 11 12

MATLAB BASICS
Subarrays
It is possible to select and use subsets of MATLAB arrays. arr1 = [1.1 -2.2 3.3 -4.4 5.5]; arr1(3) is 3.3 arr1([1 4]) is the array [1.1 -4.4] arr1(1 : 2 : 5) is the array [1.1 3.3 5.5] For two-dimensional arrays, a colon can be used in a subscript to select all of the values of that subscript. arr2 = [1 2 3; -2 -3 -4; 3 4 5]; arr2(1, :) arr2(:, 1:2:3)
9/8/2013 34

MATLAB BASICS
Subarrays
The end function: When used in an array subscript, it returns the highest value taken on by that subscript. arr3 = [1 2 3 4 5 6 7 8]; arr3(5:end) is the array [5 6 7 8] arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; arr4(2:end, 2:end) Using subarrays on the left hand-side of an assignment statement: arr4(1:2, [1 4]) = [20 21; 22 23]; (1,1) (1,4) (2,1) and (2,4) are updated. arr4 = [20 21; 22 23]; all of the array is changed.
9/8/2013 35

MATLAB BASICS
Subarrays
Assigning a Scalar to a Subarray: A scalar value on the right-hand side of an assignment statement is copied into every element specified on the left-hand side.
>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12]; >> arr4(1:2, 1:2) = 1 arr4 = 1 1 3 4 1 1 7 8 9 10 11 12
9/8/2013 36

MATLAB BASICS
Sum and Transpose
Creating a random matrix as before, we might get: 1 2 3 4 If we set this equal to A when creating it, we could sum up the columns by >>sum(A) To get ans = 4 6
To find the transpose of the matrix A, use A to get: >> A=[1 2 ;3 4] A= 1 2 3 4 >> A' ans = 1 3 2 4

9/8/2013

37

MATLAB BASICS
Special Values
MATLAB includes a number of predefined special values. These values can be used at any time without initializing them. These predefined values are stored in ordinary variables. They can be overwritten or modified by a user. If a new value is assigned to one of these variables, then that new value will replace the default one in all later calculations. >> circ1 = 2 * pi * 10; >> pi = 3; >> circ2 = 2 * pi * 10; Never change the values of predefined variables.
9/8/2013 38

MATLAB BASICS
Special Values
pi: value up to 15 significant digits i, j: sqrt(-1) Inf: infinity (such as division by 0) NaN: Not-a-Number (division of zero by zero) clock: current date and time in the form of a 6-element row vector containing the year, month, day, hour, minute, and second date: current date as a string such as 16-Feb-2004 eps: epsilon is the smallest difference between two numbers ans: stores the result of an expression
9/8/2013 39

MATLAB BASICS
Changing the data format
>> value = 12.345678901234567; format short 12.3457 format long 12.34567890123457 format short e 1.2346e+001 format long e 1.234567890123457e+001 format short g 12.346 format long g 12.3456789012346 format rat 1000/81

9/8/2013

40

MATLAB BASICS
The disp( array ) function
>> disp( 'Hello' ) Hello >> disp(5) 5 >> disp( [ 'Bilkent ' 'University' ] ) Bilkent University >> name = 'Alper'; >> disp( [ 'Hello ' name ] ) Hello Alper
9/8/2013 41

MATLAB BASICS
The num2str() and int2str() functions
>> d = [ num2str(16) '-Feb-' num2str(2004) ]; >> disp(d) 16-Feb-2004 >> x = 23.11; >> disp( [ 'answer = ' num2str(x) ] ) answer = 23.11 >> disp( [ 'answer = ' int2str(x) ] ) answer = 23

9/8/2013

42

MATLAB BASICS
The fprintf( format, data ) function
%d %f %e %g integer floating point format exponential format either floating point or exponential format, whichever is shorter new line character tab character

\n \t

9/8/2013

43

MATLAB BASICS
>> fprintf( 'Result is %d', 3 ) Result is 3 >> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 ) Area of a circle with radius 3 is 28.274334 >> x = 5; >> fprintf( 'x = %3d', x ) x= 5 >> x = pi; >> fprintf( 'x = %0.2f', x ) x = 3.14 >> fprintf( 'x = %6.2f', x ) x = 3.14 >> fprintf( 'x = %d\ny = %d\n', 3, 13 ) x=3 y = 13
9/8/2013 44

MATLAB BASICS
Data files save filename var1 var2
>> save myfile.mat x y >> save myfile.dat x ascii binary ascii binary ascii

load filename
>> load myfile.mat >> load myfile.dat ascii

9/8/2013

45

MATLAB BASICS
variable_name = expression;
addition subtraction multiplication division exponent a+b a-b axb a/b ab a+b a-b a*b a/b a^b

9/8/2013

46

MATLAB BASICS
Hierarchy of operations x=3*2+6/2 Processing order of operations is important
parentheses (starting from the innermost) exponentials (from left to right) multiplications and divisions (from left to right) additions and subtractions (from left to right)

>> x = 3 * 2 + 6 / 2 x= 9
9/8/2013 47

MATLAB BASICS
Built-in MATLAB Functions
result = function_name( input );
abs, sign log, log10, log2 exp sqrt sin, cos, tan asin, acos, atan max, min round, floor, ceil, fix mod, rem

help elfun help for elementary math functions


9/8/2013 48

MATLAB BASICS
Types of errors in MATLAB programs
Syntax errors
Check spelling and punctuation

Run-time errors
Check input data Can remove ; or add disp statements

Logical errors

9/8/2013

Use shorter statements Check typos Check units Ask your friends, assistants, instructor,
49

MATLAB BASICS
Summary

9/8/2013

help command lookfor keyword which clear clc diary filename diary on/off who, whos more on/off Ctrl+c %

Online help Lists related commands Version and location info Clears the workspace Clears the command window Sends output to file Turns diary on/off Lists content of the workspace Enables/disables paged output Aborts operation Continuation Comments
50

MATLAB : Script & Function Files

MATLAB : Script & Function Files


MATLAB Script Files
A MATLAB script file (Called an M-file) is a text (plain ASCII) file that contains one or more MATLAB commands and, optionally, comments. The file is saved with the extension ".m". When the filename (without the extension) is issued as a command in MATLAB, the file is opened, read, and the commands are executed as if input from the keyboard. The result is similar to running a program in C. The following slide is the contents of an M-file. Note that there are no prompts (>>).
9/8/2013 52

MATLAB : Script & Function Files


MATLAB Script Files
% This is a MATLAB script file. % It has been saved as g13.m". load g13.dat; %Load data file voltage = g13( : , 4); %Extract volts vector time = .005*[1:length(voltage)]; %Create time vector plot (time, voltage) %Plot volts vs time xlabel ('Time in Seconds') % Label x axis ylabel ('Voltage') % Label y axis title ('Bike Strain Gage Voltage vs Time') grid %Put a grid on graph
9/8/2013 53

MATLAB : Script & Function Files


MATLAB Script Files
The preceding file is executed by issuing a MATLAB command: >> g13 This single command causes MATLAB to look in the current directory, and if a file g13.m is found, open it and execute all of the commands. The result, in this case, is a plot of the data from g13.dat. If MATLAB cannot find the file in the current working directory, an error message will appear.
9/8/2013 54

MATLAB : Script & Function Files


MATLAB Script Files
When the file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a:\ % Make a:\ the current working directory >> g13

9/8/2013

55

MATLAB : Script & Function Files


MATLAB Function Files
A MATLAB function file (called an M-file) is a text (plain ASCII) file that contains a MATLAB function and, optionally, comments. The file is saved with the function name and the usual MATLAB script file extension, ".m".

A MATLAB function may be called from the command line or from any other M-file.
9/8/2013 56

MATLAB : Script & Function Files


MATLAB Function Files
When the function is called in MATLAB, the file is accessed, the function is executed, and control is returned to the MATLAB workspace. Since the function is not part of the MATLAB workspace, its variables and their values are not known after control is returned.
Any values to be returned must be specified in the function syntax.
9/8/2013 57

MATLAB : Script & Function Files


MATLAB Function Files
The syntax for a MATLAB function definition is: function [val1, , valn] = myfunc (arg1, , argk) where val1 through valn are the specified returned values from the function and arg1 through argk are the values sent to the function.
Since variables are local in MATLAB (as they are in C), the function has its own memory locations for all of the variables and only the values (not their addresses) are passed between the MATLAB workspace and the function.
9/8/2013 58

MATLAB : Script & Function Files


MATLAB Function Files
It is OK to use the same variable names in the returned value list as in the argument. The effect is to assign new values to those variables. As an example, the following slide shows a function that swaps two values.

9/8/2013

59

MATLAB : Script & Function Files


MATLAB Function Files
The MATLAB function must be in the current working directory. If it is not, the directory must be changed before calling the function. If MATLAB cannot find the function or its syntax does not match the function call, an error message will appear. Failure to change directories often results in the error message:
Undefined function or improper matrix assignment.
9/8/2013 60

MATLAB : Script & Function Files


MATLAB Function Files
When the function file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a:\ % Make a:\ the current working directory

9/8/2013

61

MATLAB : Script & Function Files


MATLAB Function Files
Unlike C, a MATLAB variable does not have to be declared before being used, and its data type can be changed by assigning a new value to it.
For example, the function factorial ( ) on the next slide returns an integer when a positive value is sent to it as an argument, but returns a character string if the argument is negative.

9/8/2013

62

MATLAB : Script & Function Files


MATLAB Function Files
function [n] = factorial (k) % The function [n] = factorial(k) calculates and % returns the value of k factorial. If k is negative, % an error message is returned. if (k < 0) n = 'Error, negative argument'; elseif k<2 n=1; else n = 1; for j = [2:k] n = n * j; end end
9/8/2013 63

Matlab Programming

MATLAB Programming
Matlab environment
Matlab construction Core functionality as compiled C-code, m-files Additional functionality in toolboxes (m-files)
Today: Matlab programming (construct own m-files)
Contr. Syst.

Sig. Proc

User defined

C-kernel
9/8/2013

Core m-files
65

MATLAB Programming
The Programming Environment
The working directory is controlled by >> dir >> cd catalogue >> pwd

The path variable defines where matlab searches for m-files >> path >> addpath >> pathtool >> which function
9/8/2013 66

MATLAB Programming
The programming environment
Matlab cant tell if identifier is variable or function >> z=theta; Matlab searches for identifier in the following order 1. variable in current workspace 2. built-in variable 3. built-in m-file 4. m-file in current directory 5. m-file on search path Note: m-files can be located in current directory, or in path 9/8/2013 67

MATLAB Programming
Script files
Script-files contain a sequence of Matlab commands
factscript.m
%FACTSCRIPT Compute n-factorial, n!=1*2*...*n y = prod(1:n);

Executed by typing its name >> factscript Operates on variables in global workspace Variable n must exist in workspace Variable y is created (or over-written) Use comment lines (starting with %) to document file! 9/8/2013

68

MATLAB Programming
Displaying code and getting help
To list code, use type command >> type factscript

The help command displays first consecutive comment lines >> help factscript

9/8/2013

69

MATLAB Programming
Functions
Functions describe subprograms Take inputs, generate outputs Have local variables (invisible in global workspace) [output_arguments]= function_name(input_arguments) % Comment lines <function body>

factfun.m

function [z]=factfun(n) % FACTFUN Compute factorial % Z=FACTFUN(N)

z = prod(1:n);
9/8/2013

>> y=factfun(10);

70

MATLAB Programming
Scripts or function: when use what?
Functions Take inputs, generate outputs, have internal variables Solve general problem for arbitrary parameters Scripts Operate on global workspace Document work, design experiment or test Solve a very specific problem once Exam: all problems will require you to write functions

facttest.m
% FACTTEST Test factfun
9/8/2013

N=50; y=factfun(N);

71

MATLAB Programming
Flow Control

MATLAB has five flow control constructs:


if statements switch statements for loops while loops break statements
9/8/2013 72

MATLAB Programming
Flow control - selection
SWITCH - Switch among several cases based on expression. The general form of the SWITCH statement is: SWITCH switch_expr CASE case_expr, statement, ..., statement CASE {case_expr1, case_expr2, case_expr3,...} statement, ..., statement ... OTHERWISE, statement, ..., statement END
9/8/2013 73

MATLAB Programming
switch (cont.)

Note: Only the statements between the matching


CASE and the next CASE, OTHERWISE, or END are executed. Unlike C, the SWITCH statement does not fall through (so BREAKs are unnecessary).

9/8/2013

74

MATLAB Programming
Flow control - selection

The if-elseif-else construction


if <logical expression> if height>170 disp(tall) elseif height<150 disp(small) else disp(average)

<commands>
elseif <logical expression> <commands> else <commands> end
9/8/2013

end
75

MATLAB Programming
Logical expressions
Relational operators (compare arrays of same sizes) == (equal to) ~= (not equal) < (less than) <= (less than or equal to) > (greater than) >= (greater than or equal to) Logical operators (combinations of relational operators) & (and) if (x>=0) & (x<=10) | (or) ~ (not) disp(x is in range [0,10]) Logical functions else xor isempty disp(x is out of range) any end all
9/8/2013 76

MATLAB Programming
Flow control - repetition
Repeats a code segment a fixed number of times
for index=<vector>
<statements> end The <statements> are executed repeatedly. At each iteration, the variable index is assigned a new value from <vector>. for k=1:12 kfac=prod(1:k); disp([num2str(k), ,num2str(kfac)]) end
9/8/2013 77

MATLAB Programming
Example selection and repetition
function y=fact(n) % FACT Display factorials of integers 1..n if nargin < 1 error(No input argument assigned) elseif n < 0 error(Input must be non-negative) elseif abs(n-round(n)) > eps error(Input must be an integer) end for k=1:n kfac=prod(1:k); disp([num2str(k), ,num2str(kfac)]) y(k)=kfac; end;
9/8/2013

fact.m

78

MATLAB Programming
Repetition: Animation demo
The function movie replays a sequence of captured frames Construct a movie of a 360 tour around the Matlab logo logomovie.m
% logomovie make movie of 360 degree logo tour logo; no_frames=40; dtheta=360/no_frames; for frame = 1:no_frames, camorbit(dtheta,0) M(frame) = getframe(gcf); end % now display captured movie movie(gcf,M);
9/8/2013 79

MATLAB Programming
Flow control conditional repetition
while-loops
while <logical expression> <statements> end <statements> are executed repeatedly as long as the <logical expression> evaluates to true

k=1;
while prod(1:k)~=Inf, k=k+1; end

disp([Largest factorial in Matlab:,num2str(k-1)]);


9/8/2013 80

MATLAB Programming
Solutions to nonlinear equations

Flow control conditional repetition

can be found using Newtons method

Task: write a function that finds a solution to

Given
9/8/2013

, iterate maxit times or until


81

MATLAB Programming
Flow control conditional repetition
newton.m
function [x,n] = newton(x0,tol,maxit) % NEWTON Newtons method for solving equations % [x,n] = NEWTON(x0,tol,maxit) x = x0; n = 0; done=0; while ~done, n = n + 1; x_new = x - (exp(-x)-sin(x))/(-exp(-x)-cos(x)); done=(n>=maxit) | ( abs(x_new-x)<tol ); x=x_new; end

>> [x,n]=newton(0,1e-3,10)
9/8/2013 82

MATLAB Programming
Function functions
Do we need to re-write newton.m for every new function? No! General purpose functions take other m-files as input. >> help feval >> [f,f_prime]=feval(myfun,0); myfun.m
function [f,f_prime] = myfun(x) % MYFUN Evaluate f(x) = exp(x)-sin(x) % and its first derivative % [f,f_prime] = myfun(x) f=exp(-x)-sin(x); f_prime=-exp(-x)-cos(x);
9/8/2013 83

MATLAB Programming
Function functions
Can update newton.m newtonf.m
function [x,n] = newtonf(fname,x0,tol,maxit) % NEWTON Newtons method for solving equations % [x,n] = NEWTON(fname,x0,tol,maxit) x = x0; n = 0; done=0; while ~done, n = n + 1; [f,f_prime]=feval(fname,x); dx f ( x, t ) x_new = x f/f_prime; done=(n>maxit) |dt ( abs(x_new-x)<tol ); x=x_new; end

>> [x,n]=newtonf(myfun,0,1e-3,10)
9/8/2013 84

MATLAB Programming
Function functions in Matlab
Heavily used: integration, differentiation, optimization, >> help ode45 Find the solution to the ordinary differential equation myodefun.m
function x_dot = myodefun(t,x) % MYODEFUN Define RHS of ODE x_dot(1,1)=x(2); x_dot(2,1)=-x(1)+0.1*(1-x(1)^2)*x(2);
85

9/8/2013

>> ode45(myodefun,[0 10],[1;-10]);

MATLAB Programming
Programming tips and tricks
Programming style has huge influence on program speed! slow.m tic; fast.m X=-250:0.1:250;
for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end; end; toc tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc;

9/8/2013

Loops are slow: Replace loops by vector operations! Memory allocation takes a lot of time: Pre-allocate memory! 86 Use profile to find code bottlenecks!

MATLAB Programming
Summary
User-defined functionality in m-files Stored in current directory, or on search path Script-files vs. functions Functions have local variables, Scripts operate on global workspace Writing m-files Header (function definition), comments, program body Have inputs, generate outputs, use internal variables Flow control: if...elseif...if, for, while General-purpose functions: use functions as inputs Programming style and speed Vectorization, memory allocation, profiler
9/8/2013 87

MATLAB Programming
Advanced Matlab Programming
Functions Can have variable number of inputs and outputs (see: nargin, nargout, varargin, varargout) Can have internal functions
Data types: more than just arrays and strings: Structures Cell arrays File handling Supports most C-commands for file I/O (fprintf,)
9/8/2013 88

MATLAB Programming
Object-orientation Object: structure + methods Creation, encapsulation, inheritage, aggregation Graphical user interfaces Based on handle concept for graphics Menus, buttons, slides, and interactive graphics Interfacing other codes Can call compiled C/C++ (mex), Java and ActiveX
9/8/2013 89

MATLAB: Basic Graphics

MATLAB : Basic Graphics


Section Outline
2-D plotting Graph Annotation Subplots & Alternative Axes 3-D plotting Specialized plotting routines Patches & Images Saving & Exporting Figures Introduction to Handle Graphics

MATLAB : Basic Graphics


2-D Plotting
Specify x-data and/or y-data Specify color, line style and marker symbol
(Default values used if clmnot specified)

Syntax:
Plotting single line:
plot(xdata, ydata, 'color_linestyle_marker')

Plotting multiple lines:


plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)

MATLAB : Basic Graphics


2-D Plotting - example
Create a Blue Sine Wave
x = 0:.1:2*pi; y = sin(x); plot(x,y)

plot_2d

MATLAB : Basic Graphics


Adding a Grid
GRID ON creates a grid on the current figure GRID OFF turns off the grid from the current figure GRID toggles the grid state
grid on

MATLAB : Basic Graphics


Adding additional plots to a figure
HOLD ON holds the current plot HOLD OFF releases hold on current plot HOLD toggles the hold state
x = 0:.1:2*pi;

y = sin(x);
plot(x,y,'b') grid on hold on

plot(x,exp(-x),'r:*')
addgraph

MATLAB : Basic Graphics


Controlling viewing area


ZOOM ON allows user to select viewing area
ZOOM OFF prevents zooming operations ZOOM toggles the zoom state AXIS sets axis range

[xmin xmax ymin ymax] axis([0 2*pi 0 1])

MATLAB : Basic Graphics Graph Annotation


TITLE LEGEND

YLABEL

TEXT or GTEXT

XLABEL
annotation

MATLAB : Basic Graphics

Plot Editor
Enable Plotting Editing Right click (Ctrl-LFT): on graphics objects to modify properties

Add Text Add Arrow Add Line Zoom In Zoom Out

Rotate 3D
[Edit] -> Copy Figure / Options

plotedit

MATLAB : Basic Graphics


Exercise: 2-D Plotting
Create the following graph:
fontsize (14)

sin(10t)

cos(10t)

Courier New + Bold

MATLAB : Basic Graphics


Solution: 2-D Plotting
t = 0:0.01:0.5; plot(t,sin(10*pi*t),'g-*', ... t,cos(10*pi*t),'k:o') title(['\fontsize{14}In-Phase ({\itsolid})', ... 'and Quadrature ({\itdotted}) Signals']) xlabel('\fontname{Courier New}\bfTime (\mus)') ylabel('{\it''Normalized''} Signals'); text(0.2, cos(2*pi)+0.1, '\leftarrow----\rightarrow'); text(0.175, cos(2*pi)+0.2, '^\pi/_2 phase lag'); axis([0 0.5 -1.5 1.5]); % % % % NOTE: Could have also used GTEXT or PLOTEDIT: ============================================= gtext('\leftarrow----\rightarrow'); gtext('^\pi/_2 phase lag');

plot2d_soln

MATLAB : Basic Graphics Subplots


SUBPLOT- display multiple axes in the same figure window
subplot(#rows, #cols, index) subplot(2,2,1); plot(1:10) subplot(2,2,2)

x = 0:.1:2*pi;
plot(x,sin(x)) subplot(2,2,3) x = 0:.1:2*pi; plot(x,exp(-x),r) subplot(2,2,4) plot(peaks) subplotex

MATLAB : Basic Graphics


Alternative Scales for Axes

LOGLOG Both axes logarithmic

SEMILOGY log Y linear X

SEMILOGX log X linear Y

PLOTYY 2 sets of linear axes

other_axes

MATLAB : Basic Graphics 3-D Line Plotting


plot3(xdata, ydata, zdata, 'clm', ...) z = 0:0.1:40; x = cos(z); y = sin(z); plot3(x,y,z)

plot_3d

MATLAB : Basic Graphics


3-D Surface Plotting

surf_3d

MATLAB : Basic Graphics


Exercise: 3-D Plotting
Data from a water jet experiment suggests the following non-linear model for the 2-D stress in the cantilever beams horizontal plane.
x

= e-x[sin(x)*cos(y)]
where: = localized planar stress [MPa] x = distance from end of beam [10-1m] y = distance from centerline of beam [10-1m]

For the particular setup used:


(x = {0 to 6}, y = {-3 to 3}, = = = 1, = -0.2)

Plot the resulting stress distribution

MATLAB : Basic Graphics


Solution: 3-D Plotting
B = -0.2; x = 0:0.1:2*pi; y = -pi/2:0.1:pi/2; [x,y] = meshgrid(x,y); z = exp(B*x).*sin(x).*co s(y); surf(x,y,z)
plot3d_soln

MATLAB : Basic Graphics


Specialized Plotting Routines

spec_plots

MATLAB : Basic Graphics


Specialized Plotting Routines (2)

spec_plots2

MATLAB : Basic Graphics Reduced Memory Requirements: Images


a = magic(4)
a = 16 5 9 4 2 11 7 14 3 10 6 15 Use Row 2 of colormap 13 for pixel (1,2) 8 12 1

Images represented as UINT8 - 1 byte

image(a); map = hsv(16) map = 1.0000 1.0000 1.0000 0 0.3750 0.7500 0 0 Row 2 0 .....

colormap(map) imagex

MATLAB : Basic Graphics


Example: Images

load cape image(X) colormap(map)

MATLAB : Basic Graphics Saving Figures


2 files created: .m - text file .mat - binary data file.

plot3d_soln

9/8/2013

111

MATLAB : Basic Graphics


Printing Figures
using the Dialog Box:
File Menu / Print...
>>printdlg

from Command Line:


print -devicetype -options

(Switches are optional)

Controlling Page Layout:


File Menu / Page Position
>>pagedlg
9/8/2013 112

MATLAB : Basic Graphics


Exporting Figures
Printing image to a file:
Print Dialog Box: (File / Print...) Command Line:
>>printdlg

print -devicetype -options filename

(Switches are optional)

Copying to Clipboard:
Options: (File / Preferences) Copying: (Edit / Copy Figure)
9/8/2013 113

MATLAB : Basic Graphics


Introduction to Handle Graphics
Graphics in MATLAB consist of objects Every graphics objects has a unique handle and a set of properties which define its appearance. Objects are arranged in terms of a set hierarchy
Root (Screen)

Figure

Uicontrol

Axes

Uimenu

9/8/2013

Image

Line

Patch

Surface

Text

Light

114

Hierarchy of Graphics Objects


Root object Figure object UIMenu objects Axes object UIControl objects

Surface object Line objects

Text objects

MATLAB : Basic Graphics


Obtaining an Objects Handle
1. Upon Creation
h_line = plot(x_data, y_data, ...)

2. Utility Functions
0 - root object handle gcf - current figure handle gca - current axis handle gco - current object handle
What is the current object? Last object created OR Last object clicked

3. FINDOBJ

h_obj = findobj(h_parent, 'Property', 'Value', ...) Default = 0 (root object)

MATLAB : Basic Graphics Deleting Objects - DELETE


delete(h_object)

addgraph h = findobj('Color', [0 0 1]) delete(h)

MATLAB : Basic Graphics


Modifying Object Properties
Using GET & SET

Obtaining a list of current properties:


get(h_object)

Obtaining a list of settable properties:


set(h_object)

Modifying an objects properties:


set(h_object, 'PropertyName', 'New_Value', ...)

9/8/2013

118

MATLAB : Basic Graphics


Modifying Object Properties
Using the Property Editor

Object Browser:
Hierarchical list of graphics objects

Property / Value Fields:


Selected property & current value (modify here)

Property List:
List of properties & current values for selected object

propedit

MATLAB : Basic Graphics Modifying Object Properties


Using the RIGHT CLICK

MATLAB : Basic Graphics


Working with Defaults - setting
Most properties have pre-defined 'factory' values
(Used whenever property values are not specified.)

You can define your own 'default' values to be used for creating new objects.
(Put default settings in startup.m to apply to whole session)

Syntax:
set(ancestor,'Default<Object><Property>',<Property_Val>)
Use root object (0) to apply to all new objects

MATLAB : Basic Graphics


Example: Working with Defaults
Set the Default Surface EdgeColor to Blue & create new surface.
set(0, 'DefaultSurfaceEdgeColor', 'b') h=surf(peaks(15));

Set the EdgeColor to Green


set(h, 'EdgeColor', 'g')

Reset back to Default Value


set(h, 'EdgeColor', 'default')

specifies Default value

Reset back to Factory Value


set(h, 'EdgeColor', 'factory')

defaults

specifies Factory value

MATLAB : Basic Graphics


Working with Defaults - removing
Return Default Property Value to Factory Setting:
set(gcf, 'DefaultSurfaceEdgeColor', 'factory')

OR

set(gcf, 'DefaultSurfaceEdgeColor', 'remove')

Create a new surface:


h = surf(peaks(15));

defaults

MATLAB : Basic Graphics


SUMMARY
Basic plots and graphs plot(X,Y) plot vectors or matrices hold hold current graph (for multiple plots on same graph) subplot(m,n,p) create axes in tiled positions (for multiple graphs in same figure) figure creates a new figure window (so a new plot does not replace a previous plot) Formatting Axes xlim([0 1]) sets the x-axis limits to 0 and 1 ylim([0 1]) sets the y-axis limits to 0 and 1 Annotating plots title(Figure Title) xlabel(Label for X-axis) ylabel(Label for Y-axis) 9/8/2013 124 legend(Name of line 1,Name of line 2)

Simulink

MATLAB Simulink
About Matlab and Simulink
Matlab MATLAB is a high-level language and interactive environment that enables you to perform computationally intensive tasks faster than with traditional programming languages such as C, C++, and Fortran. Simulink Simulink is a platform for multidomain simulation and Model-Based Design for dynamic systems. It provides an interactive graphical environment and a customizable set of block libraries, and can be 9/8/2013 126 extended for specialized applications.

MATLAB Simulink
Introduction to Simulink
Simulink is a software package for modeling, simulating, and analyzing dynamic systems. It supports linear and nonlinear systems, modeled in continuous time,
sampled time, or a hybrid of the two. Systems can also be multirate, i.e., have different. parts that are sampled or updated at different rates.
9/8/2013 127

MATLAB Simulink
Starting Simulink
At the Matlab prompt, type simulink The Simulink block library should appear

New and previous models can be opened from the file menu Double click an icon to open a library window
9/8/2013 128

MATLAB Simulink
Simulink block library
Sources Constant (output a constant) Step (output a step change) Sinks Scope (simulation time plot of input) Display (real-time display of input value during a simulation) To Workspace (saves the input to the matlab workspace) Linear Sum (add or subtract inputs) Nonlinear S-Function (user defined function)

9/8/2013

129

MATLAB Simulink
Simulation menu Start run the simulation Parameters configure simulation parameters Set simulation time

Simulink block diagram

Open-loop Simulink model for Simulation

9/8/2013

130

MATLAB Simulink
Closed-loop Simulink model for Simulation

Notice the negative sign, Set the step time to 0 block properties can be Set9/8/2013 the initial value to 0.5 edited by double clicking

Variables t, D and r are sent to workspace and can be plotted from the matlab command line: 131 Plot(t,D) Plot(t,r)

MATLAB Simulink
Simulink S-Function

An M-File S-Function template is available on the course website [sys,x0] = sfunc(t,x,u,flag)


t, x, u and flag are automatically passed to the Sfunction by Simulink
t system time x system state u system input

Variables in the S-Function template that must be correctly defined in terms t, x, u, and/or any intermediate variables defined by the user

x and u can be vectors or scalars depending on the number of states and inputs
9/8/2013 132

MATLAB Simulink
Simulink Example
Differential block & Integral block

9/8/2013

133

MATLAB Simulink
Example results

Pulse

Integral

Differential

9/8/2013

134

MATLAB HELP
Within Matlab Type help at the Matlab prompt or help followed by a function name for help on a specific function Online Online documentation for Matlab and Simulink at the MathWorks website

http://www.mathworks.com/access/helpdesk/he lp/techdoc/matlab.html http://www.mathworks.com/access/helpdesk/he lp/toolbox/simulink/


There are also numerous tutorials online that are easily found with a web search. Textbook 9/8/2013 Get Started by Matlab Rudra Pratap, Oxford Press 135

Anda mungkin juga menyukai