Escolar Documentos
Profissional Documentos
Cultura Documentos
MATLAB Overview
What is MATLAB?
History of MATLAB
Who developed MATLAB Why MATLAB was developed Who currently maintains MATLAB
MATLAB Overview
What is MATLAB?
MATLAB
MATrix LABoratory Interactive system Programming language
9/8/2013
MATLAB Overview
What is MATLAB (cont..2)
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
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
MATLAB BASICS
Arrays The fundamental unit of data in MATLAB
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.
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
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
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
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
9/8/2013
55
A MATLAB function may be called from the command line or from any other M-file.
9/8/2013 56
9/8/2013
59
9/8/2013
61
9/8/2013
62
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
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 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.)
9/8/2013
74
MATLAB Programming
Flow control - selection
<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
MATLAB Programming
Solutions to nonlinear equations
Given
9/8/2013
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
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
Syntax:
Plotting single line:
plot(xdata, ydata, 'color_linestyle_marker')
plot_2d
y = sin(x);
plot(x,y,'b') grid on hold on
plot(x,exp(-x),'r:*')
addgraph
ZOOM ON allows user to select viewing area
ZOOM OFF prevents zooming operations ZOOM toggles the zoom state AXIS sets axis range
YLABEL
TEXT or GTEXT
XLABEL
annotation
Plot Editor
Enable Plotting Editing Right click (Ctrl-LFT): on graphics objects to modify properties
Rotate 3D
[Edit] -> Copy Figure / Options
plotedit
sin(10t)
cos(10t)
plot2d_soln
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
other_axes
plot_3d
surf_3d
= 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]
spec_plots
spec_plots2
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
plot3d_soln
9/8/2013
111
Copying to Clipboard:
Options: (File / Preferences) Copying: (Edit / Copy Figure)
9/8/2013 113
Figure
Uicontrol
Axes
Uimenu
9/8/2013
Image
Line
Patch
Surface
Text
Light
114
Text objects
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
9/8/2013
118
Object Browser:
Hierarchical list of graphics objects
Property List:
List of properties & current values for selected object
propedit
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
defaults
OR
defaults
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
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
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