Basics on MATLABsamymziouimamcourses.weebly.com/uploads/2/7/8/4/... · MATLAB has excellent...
Transcript of Basics on MATLABsamymziouimamcourses.weebly.com/uploads/2/7/8/4/... · MATLAB has excellent...
Introduction to MATLABIntroduction to MATLABBasics on MATLAB
By D. Samy MZIOU3/15/2008
2Introduction to MatlabIntroduction to Matlab
Aims
1. To present the software
2. To introduce elementary operations
and functions.and functions.
3. To manipulate 2D and 3D graphics.
4. To introduce the notion of “files” and
“programming”.
3/15/2008 D. Samy MZIOU
p g g
3Introduction to MatlabIntroduction to Matlab
1. First Steps in MATLAB
1 1 Wh t i MATLAB1.1 What is MATLAB
MATLAB (MATrix LABoratory) is a very powerful and interactive ft k ti i d f i tifi t ti d isoftware package optimized for scientific computation and, in
particular, matrix manipulation.
With MATLAB we canWith MATLAB we can
do mathematics and computation,analyze dataanalyze data, develop algorithms, do simulation and modeling,
d hi l di l d hi l i t fproduce graphical displays and graphical user interfaces.
4Introduction to MatlabIntroduction to Matlab
MATLAB is an interpreted language (code is compiled each time it is run.
MATLAB is easy to use (Mathematical operations) and has a MATLAB is easy to use (Mathematical operations) and has a complete documentation online.
MATLAB is Excellent for manipulating large amounts of tabular data (arrays matrices) in a consistent waydata (arrays, matrices) in a consistent way.
MATLAB has excellent visualization tools (plotting data and functions)
MATLAB has Lots of built in functions for applied mathematics MATLAB has Lots of built-in functions for applied mathematics such data analysis,interpolation, linear algebra, Fourier analysis,…
MATLAB has many toolboxes (statistical, financial, symbolic,…)MATLAB is a good programming language. MATLAB allows to do numerical simulation based on numerical
analysis algorithmsMATLAB allows interfacing with programs in other language (C,
Fortran, …)
5Introduction to MatlabIntroduction to Matlab
1.2 Short History ( http://en.wikipedia.org/wiki/MATLAB )
MATLAB was invented in the late 1970s by Cleve Moler, thenh i f h i d h U i i fchairman of the computer science department at the University of
New Mexico. He designed it to give his students access toLINPACK and EISPACK without having to learn Fortran. It soonspread to other universities and found a strong audience withinspread to other universities and found a strong audience withinthe applied mathematics community. Jack Little, an engineer, wasexposed to it during a visit Moler made to Stanford University in1983 Recognizing its commercial potential he joined with Moler1983. Recognizing its commercial potential, he joined with Molerand Steve Bangert. They rewrote MATLAB in C and founded TheMathWorks in 1984 to continue its development. These rewrittenlibraries were known as JACKPAC.MATLAB was first adopted by control design engineers, Little'sspecialty, but quickly spread to many other domains. It is nowalso used in education, in particular the teaching of linear algebraand numerical analysis, and is popular amongst scientists involvedwith image processing.
6Introduction to MatlabIntroduction to Matlab
1.3 What is MATLAB useful references
Full documentation available online in HTML and PDF Full documentation available online in HTML and PDF format.
h // h k / /h l d k/h l /h l d k h lhttp://www.mathworks.com/access/helpdesk/help/helpdesk.html
Many documents on the web (http://www.google.com.sa)
ReadRead“Getting Started” section of the MATLAB manual
Notice: there are many freeware/sharewares similar to MATLAB. Forinstance SCILAB (http://www-rocq.inria.fr/scilab )
7Introduction to MatlabIntroduction to Matlab
1.4 How to run MATLAB
To run MATLAB on a PC double-click on the MATLAB icon onthe desktop
To run MATLAB on a Unix system, Type MATLAB at theprompt.
When MATLAB starts, a window appears (MATLAB Desktop) containing three smaller windows of different size: the Command Window, the Current Directory Window and the Command History Wi dWindow.
In the command window you should see a message:
T t t t d l t MATLAB H l D f th H l To get started, select MATLAB Help or Demos from the Help menu.>>
8Introduction to MatlabIntroduction to Matlab
current directory
>> Playbackdemo (‘desktop’)>> l b kd ('hi t i d ‘)
l b kd ('h l i d ')
>> playbackdemo('historywindow‘)
>> playbackdemo('currdirectory')>> playbackdemo('helpwindow')
MATLAB DESKTOPcommand windows
command history
9Introduction to MatlabIntroduction to Matlab
WindowsWindows PurposePurpose
Main windows enter variables and Command Windows Main windows, enter variables and commands, runs programs,…
Command History Window Logs commands entered in the Command WindowCommand Window
Current Directory Window Shows the files in the current repertory
Figure Window Contains output from the graphiccommandscommands
Editor Window Creates and debugs script and functions files
Help window Provides help informationHelp window Provides help information
Profiler Window improve the performance of your M-files is using profiling tools
Provides information about the variables Workspace Window Provides information about the variables that are used
10Introduction to MatlabIntroduction to Matlab
In the command window:
To type commands the cursor must be placed after the commandTo type commands the cursor must be placed after the commandprompt (>>).
Once the command typed, you have to press the “enter” key forexecuting the commandexecuting the command.
You can type many commands on the same line separatedbetween them by a comma (,) .
1.4 How to quit MATLAB
To end a MATLAB session type
quit or exit at the MATLAB prompt.
Click on the symbol X on the upper right of the MATLAB windowClick on the symbol X on the upper right of the MATLAB window.
11Introduction to MatlabIntroduction to Matlab
1.5 Help me MATLAB!
To get started, type one of these commands:
help: Opens a MATLAB help at the prompt.helpwin: Opens a MATLAB help GUIhelpdesk: Opens a MATLAB hypertext help browserd ( ) S h MATLAB d idemo(s): Starts the MATLAB demonstration
You can click on the icon on the MATLAB window?
You can learn how to use any MATLAB command by typing helpfollowed by the name of the command, for example >>help sin.
You can also use the lookfor command, which searches the helpentries for all MATLAB commands for a particular word.you could type >> lookfor inverse. MATLAB responds with the names ofthe commands that have the searched word in the first line of the helpthe commands that have the searched word in the first line of the helpentry. You can search the entire help entry for all MATLAB commands bytyping >> lookfor –all inverse.
12Introduction to MatlabIntroduction to Matlab
REMARK on the “HELP” command
For example, help solve will display documentation for solve. p , p p y
Unless you have a large monitor, the output of help solve will
not fit in your MATLAB command window, and the beginning of
the documentation will scroll quickly past the top of the
screen. You can force MATLAB to display information one
screenful at a time by typing more on.
You press the space bar to display the next screenful, or ENTER
to display the next line; type help more for details. Typing
more on affects all subsequent commands, until you type
more off.
13Introduction to MatlabIntroduction to Matlab
2.1 First Steps :
To allow MATLAB to carry out 1 + 1 type the following at the prompt:To allow MATLAB to carry out 1 + 1, type the following at the prompt:>> 1+1
MATLAB responds withans =ans2
The result is logged in variable called “ans”. In fact “ans” is now a variable that you can use again For example you can type “ ans*ans”variable that you can use again. For example you can type ans ansto check that 2 × 2 = 4:>> ans*ansans =4
Here MATLAB has updated the value of “ans” to be “4”.
h i bl “ ” i h d f l i blThe variable “ans” is the MATLAB default variable. It changes each time that you execute a command.
14Introduction to MatlabIntroduction to Matlab
Remark :Remark :
The spacing of operators in formulae does not matter. The following formulas both give the same answer:g
>> 1+3 * 2-1 / 2*4
>> 1 + 3 * 2 - 1 / 2 * 4
The order of operations is made clearer to readers of your MATLAB code if you type carefully:
>> 1 + 3*2 - (1/2)*4
15Introduction to MatlabIntroduction to Matlab
2.2 Matrices
The basic object that MATLAB deals with is a matrix A matrix is an The basic object that MATLAB deals with is a matrix. A matrix is an array of numbers. For example the following are matrices:
1 2 3 9i⎛ ⎞⎛ ⎞
⎜ ⎟⎜ ⎟( )
11 2 0 0 0 1 6 1 2 4 4 2
1( 2 ) 3 1
ei
s q r t p i
⎜ ⎟⎜ ⎟ −⎜ ⎟⎜ ⎟−⎜ ⎟−⎜ ⎟⎜ ⎟⎜ ⎟
⎝ ⎠ ⎝ ⎠
The size of a matrix is the number of rows by the number of columns.The first matrix is a 3×3 matrix. The (2,3)-element is one million “1e6”th t t d f 1 106 d th (3 2) l t i i 3 14159
3 1⎝ ⎠ ⎝ ⎠
that stands for 1 × 106 , and the (3,2)-element is pi = π = 3.14159 ...
The second matrix is a row-vector, the third matrix is a column-vector containing the number i, which is a pre-defined MATLAB variable equal g , p qto the square root of −1. The last matrix is a 1 × 1 matrix, also called a scalar.
16Introduction to MatlabIntroduction to Matlab
2.3 Variables and assignmentsVariable_name = numerical value or computable expressionVariables in MATLAB are named objects and are assigned using
the equals sign “=“. They can contain
d l l ttupper and lowercase lettersany number of ‘_’ charactersnumerals.
They must start with a letter They must start with a letter.
Matlab is case sensitive: A and a are different variables.
Don’t use a MATLAB built-in functions as a variable
>> a = 1
The following are valid MATLAB variable assignments:
>> speed = 1500>> BeamFormerOutput_Type1 = v*Q*v’>> name = ’John Smith’
17Introduction to MatlabIntroduction to Matlab
>> 42for1 = ’yes’>> first one = 2>> clear=4*3,pi=72, ans=pi*5
These are invalid assignments:
To assign a variable without getting an echo from MATLAB we use the co semi-colon character “;” . Compare the followings:
To assign a variable without getting an echo from MATLAB we use the co semi-colon character “;” . Compare the followings:p gp g
>> a = 2; >>
>> a = 2 a=
2
Try typing the following:Try typing the following:>> a = 2;b = 3;>> c = a+b; >> who Lists the variables currently in the memory>> h S h ith i f ti b t th i b t d l>> whos Same as who with information about their bytes and class>> clear Removes all variables from the memory>> home Clean the command window display >> clc
18Introduction to MatlabIntroduction to Matlab
2.4 How to generate a series of numbers
To generate a series of numbers we write all the numbers in square
brackets and we separate them either using commas or blanks.
>> [1 2 3 4 5] >> [1,2,3,4,5]
ans =
1 2 3 4 5
ans =
1 2 3 4 5
It is your turn! Try some examples yourselves
19Introduction to MatlabIntroduction to Matlab
2.5 How to generate a series of numbers (The Colon Operator “:”)
To generate a vector of equally-spaced elements MATLAB provides the colon operator “:”.
>> 1 2 10>> 1:5
ans =
>> u=1:2:10
u =
1 2 3 4 5 1 3 5 7 9
The syntax “x:y” means roughly “generate the ordered set of numbers from x to y with increment 1 (default value) between them.”
Th t “ d ” hl “ t th d d t The syntax “x:d:y” means roughly “generate the ordered set of numbers from x to y with increment d between them.”
20Introduction to MatlabIntroduction to Matlab
2.6 The command “Linspace”
To generate a vector of evenly spaced points between two end points, you can use the command linspace(startpoint,endpoint,npoints )
>> x = linspace(0,1,10)x =Columns 1 through 70 0 1111 0 2222 0 3333 0 4444 0 5556 0 66670 0.1111 0.2222 0.3333 0.4444 0.5556 0.6667Columns 8 through 100.7778 0.8889 1.0000
The previous command generates 10 evenly spaced points from 0 to 1.
Typing linspace(startpoint,endpoint) will generate a vector of 100 yp g p ( p , p ) g
points.
21Introduction to MatlabIntroduction to Matlab
3 Typing into MATLAB
3.1 Command Line Editingg
If you make a mistake when entering a MATLAB command, you do not have to type the whole line again. The arrow keys can be used to save much typing:
↑ ctrl-p Recall previous line↓ ctrl-n Recall next line
much typing:
← ctrl-b Move back one character→ ctrl-f Move forward one characterctrl-→ ctrl-r Move right one wordctrl-← ctrl-l Move left one wordhome ctrl-a Move to beginning of lineend ctrl-e Move to end of lineesc ctrl-u Clear linedel ctrl-d Delete character at cursorbackspace ctrl-h Delete character before cursor
ctrl-k Delete (kill) to end of line
22Introduction to MatlabIntroduction to Matlab
23Introduction to MatlabIntroduction to Matlab
3.2 Long Lines
If you want to type a MATLAB command that is too long to fit on one line, you can continue on to the next by ending with a space followed by three full stops “…” For example, to type an expression with long variable names:variable names:
>> Final_Ans = Matrix(row_indices,column_indices) + ...Another_vector*SomethingElse;
Or to define a long text string:
>> Mission = [’DST’’s objective is to give advice that’ ...’is professional, impartial and informed on the’ ...’application of science and technology that is best’ ...’suited to French’’s defence and security needs.’];
24Introduction to MatlabIntroduction to Matlab
3.3 Copying and Pasting
Your windowing system’s copy and paste facility can be used to enter text into the MATLAB command line. For example all of MATLAB’S built-in commands have some helpful text that can by accessed by typing helpp y y yp g pfollowed by the name of the command. Try typing help contour into MATLAB and you will see a description of how to create a contour plot.
At the end of the help message is an example You can use the mouse to At the end of the help message is an example. You can use the mouse to select the example text and paste it into the command line. Try it now and you should see a contour plot appear in the figure window.
25Introduction to MatlabIntroduction to Matlab
3.4 Basic Datatypes
double: Floating point number, the most common datatype in MATLABh d
>> a = 1; whos ('a');
Name Si e B tes Class
➔ Other numeric datatypes: float, int32, uint8, ... rather uncommon
Name Size Bytes Classa 1x1 8 double array
Grand total is 1 element using 8 bytes
>> a = complex(1,-2) >> a = 1-2*i
Complex numbers:
Warning: “i” can bea =1.0000 - 2.0000i
a =1.0000 - 2.0000i
Warning: i can beredefined
(overwritten)!
StringsStrings >> a = ['test123']a =test123
26Introduction to MatlabIntroduction to Matlab
3.5 Advanced Datatypes
Cell Arrays: Generalised matrixy➔ Elements can have differing datatypes➔ Elements can have different sizes
>> a = {[1,2,3], 'test123'}a =
[1x3 double] 'test123'
Structures➔ Combine various data in a 'field/value' type structure➔ Fields and associated datatypes do not have to be declared( d h t ti )(and can change at run-time)
>> a.b = 2; a.c = [2,3,4];>> aa =a
b: 2c: [2 3 4]
27Introduction to MatlabIntroduction to Matlab
3.6 Matrices
3 6 1 Typing Matrices3.6.1 Typing Matrices
To type a matrix into MATLAB you must begin with a left square bracket [
l hseparate elements in a row with commas or spacesuse a semicolon “;” to separate rows or the “enter” keyend the matrix with the right square bracket ].
>> [1 2 3>> a = [1 2 3;4 5 6;7 8 9]
a =
>> a = [1,2,3;4,5,6;7,8,9]
a =
>> a = [1 2 34 5 67 8 9]
1 2 34 5 67 8 9
1 2 34 5 67 8 9
a =
1 2 34 5 67 8 9 4 5 67 8 9
28Introduction to MatlabIntroduction to Matlab
3.6.2 Arithmetic operators
A. For scalars
Operator Description Example
+ Addition 5+3
- Subtraction 4-2
.* Multiplication 3.*4
./ Right division 4./2g
.\ Left division 2.\4
.^ Power 2.^5
Order of precedence:1. Parenthesis 2. Exponentiation3. Multiplication and Division4. Addition and Subtraction
29Introduction to MatlabIntroduction to Matlab
B. For matricesOperator Description Example
+ Addition A+B
- Subtraction A-B
* Multiplication A*B
/ Right division A/B/ Right division A/B
\ Left division B\A
^ Power A^2
.’ Transpose A.’
: Column operator A(:,1:3)
O d f dOrder of precedence:1. Parenthesis 2. Exponentiation3. Multiplication and Division3. Multiplication and Division4. Addition and Subtraction5. Column operator
30Introduction to MatlabIntroduction to Matlab
C. Operator PrecedenceYou can build expressions that use any combination of arithmetic, relational,
and logical operators. Precedence levels determine the order in whichMATLAB l t i Withi h d l l tMATLAB evaluates an expression. Within each precedence level, operatorshave equal precedence and are evaluated from left to right. Theprecedence rules for MATLAB operators are shown in this list, orderedfrom highest precedence level to lowest precedence level:
1. Parentheses ()2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix
power (^) 3. Unary plus (+), unary minus (-), logical negation (~)4. Multiplication (.*), right division (./), left division(.\), matrix
multiplication (*), matrix right division (/), matrix left division (\)
5. Addition (+), subtraction (-)6. Colon operator (:)7. Less than (<), less than or equal to (<=), greater than (>), greater
than or equal to (>=), equal to (==), not equal to (~=)8. Element-wise AND (&)8. Element wise AND (&)9. Element-wise OR (|)
31Introduction to MatlabIntroduction to Matlab
3 6 2 B ilt i MATLAB V i bl3.6.2 Built-in MATLAB Variables
Name Meaning
ans value of an expression when that expression is not assigned toa variable
eps floating point precision (2.2204e-016)
pi π, (3.141492 . . .)
l l i i fl i i b (1 7977 308)realmax largest positive floating point number (1.7977e+308)
realmin smallest positive floating point number (2.2251e-308)
Inf ∞, a number larger than realmax,
NaN not a number, the result of evaluating 0/0
i, j preassigned to square root of −1
32Introduction to MatlabIntroduction to Matlab
3 6 3 B ilt i MATLAB F ti3.6.3 Built-in MATLAB Functions
Name Meaning
sqrt(x) Square root
exp(x) exponential
b ( ) Ab l t l abs(x) Absolute value
log(x), log10(x) Natural and base 10 logarithm
factorial(x) Factorial function
sin(x),cos(x),tan(x),cot(x) Trigonometric functions
round(x) Round to the nearest integer
fix(x) Round towards zerofix(x) Round towards zero
ceil(x) Round towards infinity
floor(x) Round towards minus infinity
rem(x y) Remainder when x is divided by yrem(x,y) Remainder when x is divided by y
sign(x) Signum function
33Introduction to MatlabIntroduction to Matlab
3 6 4 C t ti M t i
Matrices can be made up of submatrices. This process is called concatenation. The pair of square brackets “ []” is the concatenation Matrices can be made up of submatrices. This process is called concatenation. The pair of square brackets “ []” is the concatenation
3.6.4 Concatenating Matrices
operator. Try this:operator. Try this:
>> A = [1 2 3;4 5 6;7 8 9] % Generate a matrix A
>> B= [A 10*A ; -A [1 0 0;0 1 0;0 0 1]] % Create a matrix B by concatenation
B =
1 2 3 10 20 304 5 6 40 50 607 8 9 70 80 90-1 -2 -3 1 0 0-4 -5 -6 0 1 0-7 -8 -9 0 0 1
34Introduction to MatlabIntroduction to Matlab
3 6 5 C t ti M t i Th f ti “ t”3.6.5 Concatenating Matrices: The function “repmat”
The “repmat” function can be used to replicate a matrix. For instance
>> A = [1 2; 3 4]>> A [1 2; 3 4]A =
1 23 4
>> B=repmat(A,2,3)B =
1 2 1 2 1 23 4 3 4 3 41 2 1 2 1 23 4 3 4 3 4
35Introduction to MatlabIntroduction to Matlab
3 7 U f l M t i t3.7 Useful Matrix generators
MATLAB provides four easy ways to generate certain simple matrices.These are :1. zeros : a matrix filled with zeros2. ones : a matrix filled with ones3. rand : a matrix with uniformly distributed random elements
randn : a matrix with normally distributed random elementsrandn : a matrix with normally distributed random elements4. eye : identity matrix
To tell MATLAB how big these matrices should be you give the functionsthe number of rows and columns. For example:
>> a = zeros(2,3)
a =0 0 00 0 0
36Introduction to MatlabIntroduction to Matlab
>> b = ones(2,2)/2b =0 5000 0 5000
>> u = rand(1,5)u =0 9218 0 7382 0 1763 0 4057 0 93550.5000 0.5000
0.5000 0.50000.9218 0.7382 0.1763 0.4057 0.9355
>> n = randn(5,5)n =
-0.4326 1.1909 -0.1867 0.1139 0.29441 6656 1 1892 0 7258 1 0668 1 3362
>> eye(3)ans =
1 0 0-1.6656 1.1892 0.7258 1.0668 -1.33620.1253 -0.0376 -0.5883 0.0593 0.71430.2877 0.3273 2.1832 -0.0956 1.6236
-1.1465 0.1746 -0.1364 -0.8323 -0.6918
1 0 00 1 00 0 1
37Introduction to MatlabIntroduction to Matlab
3.7 Subscripting
>> u = rand(1,5)u =u 0.9218 0.7382 0.1763 0.4057 0.9355
Individual elements in a matrix are denoted by a row index and a column index To pick out the third element of the vector u type:column index. To pick out the third element of the vector u type:
>> u(3)ans =
0 17630.1763
You can use the vector [1 2 3] as an index to u. To pick the first three elements of u type :
>> u([1 2 3])ans =
0.9218 0.7382 0.1763
Remembering what the colon operator does, you can abbreviate this to
38Introduction to MatlabIntroduction to Matlab
>> u(1:3)>> u(1:3)ans =0.9218 0.7382 0.1763
You can also use a variable as a subscript:
>> i = 1:3;>> u(i)
ans =0.9218 0.7382 0.1763
Two dimensional matrices are indexed the same way, only you y, y yhave to provide two indices:
39Introduction to MatlabIntroduction to Matlab
>> A = [1 2 3;4 5 6;7 8 9]A =
1 2 34 5 67 8 9
>> a(3,2)ans =ans
8>> A(2:3,3)ans =
69
>> A(2,:)ans = The last two examples use the
l b l i d hi h ans
4 5 6>> A(:,3)ans =
3
colon symbol as an index, which matlab interprets as the entire row or column.
369
40Introduction to MatlabIntroduction to Matlab
If a matrix is addressed using a single index, matlab counts the index down successive columns:
>> A(4)ans =2>> A(8)ans =63 8 End as a subscript3.8 End as a subscript
To access the last element of a matrix along a given dimension, use end as a subscript (MATLAB version 5 or later). This allows you to go to the final element without knowing in advance how big the matrix is. Forexample:
>> Q = 4:10>> Q 4:10Q =
4 5 6 7 8 9 10
41Introduction to MatlabIntroduction to Matlab
>> Q(end)>> Q(end)ans =
10>> Q(end-4:end)ans =
6 7 8 9 10>> Q(end-2:end)ans =ans
8 9 10
>> Q = [spiral(3) [10;20;30]]Q =Q =
7 8 9 106 1 2 205 4 3 30This technique works
f t di i l >> Q(end,end)ans =30>> Q(2,end-1:end)
for two-dimensional matrices as well:
Q(2,end 1:end)ans =2 20
42Introduction to MatlabIntroduction to Matlab
>> Q(end-2:end,end-1:end)ans =
9 102 202 203 30
>> Q(end-1,:)ans =
6 1 2 20
3.9 Deleting Rows or Columns
To get rid of a row or column set it equal to the empty matrix [].
>> A = [1 2 3;4 5 6;7 8 9]A =
1 2 34 5 67 8 97 8 9
43Introduction to MatlabIntroduction to Matlab
>> A(:,2) = [ ]A =
1 31 34 67 9
3.10 Transpose
To convert rows into columns use the transpose symbol ’ :
>> A’ans =ans =
1 4 73 6 9
44Introduction to MatlabIntroduction to Matlab
>>B= [[1 2 3]’ [4 5 6]’]B =
1 42 52 53 6
Be careful when taking the transpose of complex matrices. The transpose operator takes the complex conjugate transpose. p p p j g p
If z is the matrix:1 0− i0 + 2i 1 + i0 + 2i 1 + i
then z’ is:1 0− 2i0 + i 1 − i .
To take the transpose without conjugating the complex elements, use the ’ operator In this case z ’ is:the . operator. In this case z. is:1 0 + 2i
0 − i 1 + i .
45Introduction to MatlabIntroduction to Matlab
4. Graphics in MATLAB
0 . 5
1
0 1 2 3 4 5 6 7 8 9 1 0-1
-0 . 5
0
0 1 2 3 4 5 6 7 8 9 1 0
5
P e a k s
-3 -2 -1 0 1 2 3
-3-2
-10
12
3
-5
0
xy
46Introduction to MatlabIntroduction to Matlab
figure Create a new figure
4.1 Main functions
subplot Create many axis
grid Display a grid
axis Define the limits of axis
hold Keep the plots
close Close figures
title Insert a title in the graphic
xlabelylabel Label the axisylabelzlabel
Label the axis
text, gtext Insert comment
legend Display a legend
To put mathematics in labels you can use matlab’s backslashnotation (familiar to users of the TEX typesetting system)
47Introduction to MatlabIntroduction to Matlab
4.2 2D Graphics
PLOT(X Y) PLOT(X1 Y1 X2 Y2 X3 Y3 )
plot Sketch curves or clouds of points
semilogx Plot semi-logarithmic curves
PLOT(X,Y) or PLOT(X1,Y1,X2,Y2,X3,Y3,...)
semilogy
loglog Plot semi-logarithmic curves
polar Plot graphs in polar coordinates
plotyy Plot two curves in the same graph with their own axis systemplotyy Plot two curves in the same graph with their own axis system
ezplot Plot functions
ezpolar Plot functions in polar coordinates
zoom Graphic zoomzoom Graphic zoom
Plot symbols and colors may be obtained when we use one of the 4 first previous commands, by adding a string S in those commands. first previous commands, by adding a string S in those commands.
PLOT(X,Y,S) or PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...)
48Introduction to MatlabIntroduction to Matlab
0 . 8
1
>> x=linspace(1,10,20);>> y=sin(x);z=cos(x);>> plot(x,y,’-.',x,z,'r')- 0 . 4
- 0 . 2
0
0 . 2
0 . 4
0 . 6
>> plot(x,y, . ,x,z, r )
1 2 3 4 5 6 7 8 9 1 0- 1
- 0 . 8
- 0 . 6
0
0 . 5
1
0
0 . 5
1
>> t = 0: 1:2*pi;
- 1 - 0 . 5 0 0 . 5 1- 1
- 0 . 5
- 1 - 0 . 5 0 0 . 5 1- 1
- 0 . 5
0 . 5
1
0 . 5
1
>> t = 0:.1:2*pi;>> subplot(2,2,1)>> plot(cos(t),sin(t))>> subplot(2,2,2)>> plot(cos(t),sin(2*t))
- 1 - 0 . 5 0 0 . 5 1- 1
- 0 . 5
0
- 1 - 0 . 5 0 0 . 5 1- 1
- 0 . 5
0>> subplot(2,2,3)>> plot(cos(t),sin(3*t))>> subplot(2,2,4)>> plot(cos(t),sin(4*t))
49Introduction to MatlabIntroduction to Matlab
Symbol Color Symbol marker
4.3 Graphic symbols
y
y yellow
m magenta
c cyan
r red
+ plus
º circle
* star
· pointr red
g green
b blue
w white
k black
p
x X-mark
s square
d diamond
^ triangle upk black
Symbol Style
― solid
triangle up
v triangle down
> Triangle right
< Triangle left
p pentagramso d
: dotted
― · dashpot
― ― dashed
none no line
p pentagram
H hexagram
none no marker
none no line
50Introduction to MatlabIntroduction to Matlab
4.4 Clearing the Figure Window
You can clear the plot window by typing clf, which stands for ‘clearYou can clear the plot window by typing clf, which stands for clearfigure’. To get rid of a figure window entirely, type close. To get rid ofall the figure windows, type close all. New figure windows can becreated by typing figure.
So far we have allowed matlab to choose the axes for our plots. You can change the axes in many ways:
4.5 Axes
axis([xmin xmax ymin ymax ]) sets the axes’ minimum and maximum values.
• axis square makes the axes the same length• axis equal makes the axes the same scale• axis tight sets the axes limits to the range of the data• axis auto allows matlab to choose axes limits• axis auto allows matlab to choose axes limits• axis off removes the axes leaving only the plotted data• axis on puts the axes back again
51Introduction to MatlabIntroduction to Matlab
4.6 3D Graphics
1. Elementary commands (using matrix)plot3 Sketch linear curves and clouds of points
mesh Sketch a matrix under a meshed curve
surf Sketch a matrix under a surfaced curve
2. Elementary commands (math functions)ezplot3 Sketch 2D functions and parametric functions
h Sk t h 2D f ti d t i f ti d h d ezmesh Sketch 2D functions and parametric functions under a meshed curve
ezsurf Sketch 2D functions and parametric functions under a surfaced curve
3 Tools commands3. Tools commandshidden Transparent meshing
shading Color smoothing
light lightinglight lighting
colorbar Add a bar of color
colormap Table of color
52Introduction to MatlabIntroduction to Matlab
Examples:
>> t=0:.1:2*pi;>>plot3(cos(3*t),sin(3*t),t)
>> [X,Y]=meshgrid(-10:10);>> Z=sqrt(X.^2+Y.^2);>> mesh(X,Y,Z)
53Introduction to MatlabIntroduction to Matlab
An interesting function: peaks function
222222 )1(53)1(2 1)1(10)1(3 yxyxyx eeyxxexz −+−−−+−− −−−−−=3
)5
()( y
>> [X Y Z]=peaks;>> [X,Y,Z]=peaks;>> mesh(X,Y,Z)
>> [X Y Z]=peaks;>> [X,Y,Z]=peaks;>> surf(X,Y,Z)
54Introduction to MatlabIntroduction to Matlab
h di i t>> shading interp
>> axis tight;
>> colorbar;
55Introduction to MatlabIntroduction to Matlab
>> [X,Y,Z]=peaks;>> contour(X,Y,Z)
>> [X,Y,Z]=peaks;>> plot3(X,Y,Z)
>> [X,Y,Z]=peaks;>> surfc(X,Y,Z);( , , );>> shading flat;
56Introduction to MatlabIntroduction to Matlab
Suppose we have the set of (X,Y) coordinates 1,1 1,2 1,3 1, 42,1 2,2 2,3 2, 4
( , )3 1 3 2 3 3 3 4
X Y
⎛ ⎞⎜ ⎟⎜ ⎟=⎜ ⎟
( , )3,1 3, 2 3,3 3,44,1 4,2 4,3 4, 4⎜ ⎟⎜ ⎟⎝ ⎠
The (x,y) can be split into two matrices
⎛ ⎞ ⎛ ⎞1 2 3 41 2 3 41 2 3 4
X
⎛ ⎞⎜ ⎟⎜ ⎟=⎜ ⎟
1 1 1 12 2 2 23 3 3 3
Y
⎛ ⎞⎜ ⎟⎜ ⎟=⎜ ⎟1 2 3 4
1 2 3 4⎜ ⎟⎜ ⎟⎝ ⎠
3 3 3 34 4 4 4⎜ ⎟⎜ ⎟⎝ ⎠
This is meshgrid principle
>> x=[1:4];y=[1:4]; x [1:4];y [1:4];
>> [X,Y]=meshgrid(x,y)
57Introduction to MatlabIntroduction to Matlab
4.7 Color Maps
• Matlab uses a matrix called colormap to color surfacesor images. or images. • The colormap is a list of triplets corresponding To the intensities between 0 and 1of the red, green and blue.
Red Green Blue Color0 0 0 Black
1 1 1 White
1 0 0 Red
0 1 0 Green
0 0 1 Blue
1 1 0 Yellow
1 0 1 Magenta
0 1 1 Cyan
G.5 .5 .5 Gray
.5 0 0 Dark red
1 .62 .4 Dark orange
You can create your own color maps or use any Matlab predefined color mapshsv hot gray bone copper pink white flag lines colorcube jet
prism cool autumn spring winter summer
58Introduction to MatlabIntroduction to Matlab
Carry out the following commands and observe
>> peaks;>> Colormap(gray(8))
>> m=gray(8);>> Imagesc(Colormap(m))
59Introduction to MatlabIntroduction to Matlab
4.8 Specialized graphs
Bars and surfacesbar vertical barsbar vertical bars
barh Horizontal bars
bar3 3D vertical bars
bar3h 3D Horizontal bars
area display surfaces
piespie Display a pie
pie3 Display a 3D pie
histogramshist Display an histogram of a certain distribution
Discrete datastem Display a sequence of discrete values
stem3 3D display
stairs Display stairs, echelons
60Introduction to MatlabIntroduction to Matlab
vectorscompass Display vectors centered at 0
feather Display equally spaced vectors along an axis
quiver Display vectors in a plane
quiver3 Display vectors in a space
Level linesclabel Display level lines labels
contour Display level lines in a plane
3 Di l 3D l l licontour3 Display 3D level lines
contourf Display level lines by filling the spaces
61Introduction to MatlabIntroduction to Matlab>> t=[-2:2]’;>> y=[5 2 1;8 7 3; 9 8 7; 5 5 5; 4 3 2];
>> bar(t,y) >> bar(t,y,’stack’)
>> bar3(t,y) >> area(t,y)
>> pie([31 15 8]) >> hist(randn(1000,3))
62Introduction to MatlabIntroduction to Matlab
63Introduction to MatlabIntroduction to Matlab
5. Complement on Matrix manipulation
5.1 Relational operations Example
< > Less than/greater than
<= Less than or equal to
5.1 Relational operations >> A=rand(4,3)>> B=(A>.2)&(A<0.8)>> C=A.*B>> D=(A~=A(1 1))
>= Greater than or equal to
== Equal to
~= Not equal to
>> D=(A =A(1,1))
q
5.2 Logical operations
& and : Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elementsother elements.
| or : Returns 1 for every element location that is true (nonzero) in either one or the other, or both arrays, and 0 for all other elements.
~ Not : Complements each element of the input arrayp p y
xor or (exclusif) : Returns 1 for every element location that is true (nonzero) in only one array, and 0 for all other elements.
64Introduction to MatlabIntroduction to Matlab
5.3 Operator Precedence
• You can build expressions that use any combination of arithmetic, relational, and logicaloperators.p
• Precedence levels determine the order in which MATLAB evaluates an expression. Withineach precedence level, operators have equal precedence and are evaluated from left to right.
• The precedence rules for MATLAB operators are shown in this list, ordered from highestprecedence level to lowest precedence level:p p
1. Parentheses ()2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix
power (^) power (^) 3. Unary plus (+), unary minus (-), logical negation (~)4. Multiplication (.*), right division (./), left division(.\), matrix
multiplication (*), matrix right division (/), matrix left division (\)p ( ), g (/), (\)
5. Addition (+), subtraction (-)6. Colon operator (:)7. Less than (<), less than or equal to (<=), greater than (>), greater than
or equal to (>=), equal to (==), not equal to (~=)8. Element-wise AND (&)9. Element-wise OR (|)
65Introduction to MatlabIntroduction to Matlab
>> a|b&c is similar to >> a|(b&c) Built-in functions
>> A = [3 9 5];>> B = [2 1 5];>> C = A./B.^2C =
and(A,B) equivalent to A & Bor(A,B) equivalent to A | Bnot(A) equivalent to ~A
C 0.7500 9.0000 0.2000
>> C = (A./B).^2C C =
2.2500 81.0000 1.0000Returns 1 for a vector where all elements of the vector are true (nonzero), and 0 if all elements are not trueallReturns 1 for a vector where any element of the vector is true (nonzero), and 0 if no elements are true.anyand 0 if all elements are not true
Find indices and values of nonzero elementsfind
Note The all and any functions ignore any NaN values in the input arrays
Sort array elements in ascending or descending ordersort
Find indices and values of nonzero elementsfind
66Introduction to MatlabIntroduction to Matlab
>> X = [1 0 4 3 0 0 0 8 6];>> X = [1 0 4 -3 0 0 0 8 6];>> indices = find(X)>> find(X > 2)>> find(X == 0)
5.4 some functions
mean Returns the mean values of the elements along different dimensions of an array
max, min Returns the largest (smallest) element along different dimensions of an array,
sum Return the sum of the elements along different dimensions of an array
diff Calculates differences between adjacent elements of a vector.diff
prod Returns the products of the elements
cumsum Returns the cumulative sum along different dimensions of an array.
cumprod Returns the cumulative product along different dimensions of an array.
67Introduction to MatlabIntroduction to Matlab
examples
>> a=rand(1,5)>> max(a)
>> sort(a)>> sort(A)
examples
>> A=rand(3,6)>> max(A)>> max(max(A))
>> mean(a)>> mean(A)>> max(A)>> max(max(A))>> max(max(A))
d t( b) t th l d t f th t d bdot(a,b) returns the scalar product of the vectors a and b
Cross(a,b) returns the cross product of the vectors a and b.
>> a = [1 2 3]; b = [4 5 6];>> c = cross(a,b)>> d = dot(a b)>> d = dot(a,b)
68Introduction to MatlabIntroduction to Matlab
The format Function : controls the numeric format of the valuesdisplayed by MATLAB. The function affects only how numbers are
5.4 Format functions
displayed by MATLAB. The function affects only how numbers aredisplayed, not how MATLAB computes or saves them.
>> x = [4/3 1.2345e-6]
format short 1.3333 0.0000
format short e 1.3333e+000 1.2345e-006
format short g 1.3333 1.2345e-006
format long 1.33333333333333 0.00000123450000
format long e 1.333333333333333e+000 1.234500000000000e-00
format long g 1.33333333333333 1.2345e-006
format bank 1.33 0.00
format rat 4/3 1/810045
Special Characters % : Insert comment line into code
>> x=[1:5] %create an row vector from 1 to 5 increment 1
69Introduction to MatlabIntroduction to Matlab
6. M-Files
It is used for solving complicated problems. There are two different kinds of M-files: • Script M-files • Function M-files.
M files are ordinary text files containing MATLAB commands You can M-files are ordinary text files containing MATLAB commands. You can create and modify them using any text editor or word processor that is capable of saving files as plain ASCII text. (Such text editors include notepad in Windows or emacs, winedit, and vi in UNIX.) More p , , )conveniently, you can use the built-in Editor/Debugger, which you can start by typing edit, either by itself (to edit a new file) or followed by the name of an existing M-file in the current working directory. You can also use the File menu or the two leftmost buttons on the tool bar to start use the File menu or the two leftmost buttons on the tool bar to start the Editor/Debugger, either to create a new file or to open an existing file. Double-clicking on an M-file in the Current Directory browser will also open it in the Editor/Debugger
70Introduction to MatlabIntroduction to Matlab
All Matlab commands, functions and operations can be done in an editortext file. To open an editor text file you click on the menu FILE/New oruse that matlab command >>edit
Once you have finished to type your commands you have to save it by giving it a name under extension .m
Matlab save all files in the default repertory C:\MATLAB7\work
>> Edit trial1.m % edit a Matlab file named trial1
Then type the following commands in this text editorx=[1:0.1:10];y=sin(x);plot(x,y,'r-.') and save the file trial1.m
To run a file in Matlab command window prompt we have to type thep p ypname of the file without its extension (Matlab recognize it)
Type in the Matlab window prompt>> trial
71Introduction to MatlabIntroduction to Matlab
A sequence of instructions in a file is called a SCRIPT
(For the commentaries use % character)
If you want to see the command during the script carrying out you have to use the command
h / ff >> echo on/off
Exercise:
Type echo on on the MATLAB prompt and run the file trial1.m
72Introduction to MatlabIntroduction to Matlab
A practical example :
Open a new file and call it Peaks1.mE t th f ll i d d th filEnter the following commands and run the file.subplot(2,1,1)rv=linspace(.3,1,50);thv=linspace(pi/4,5*pi/4,50);p (p / , p / , );[r,th]=meshgrid(rv,thv);x=r.*cos(th); y=r.*sin(th);plot(x,y,’.’)
Reopen the file Peaks1.m. Go to the end of the file and enter the following commandsubplot(2,1,2)
mesh(x,y,peaks(50)+10*x)
Carry out the fileCarry out the file.
73Introduction to MatlabIntroduction to Matlab
Another example:
Create the file task1.m that contains the following script and execute it
echo on
% Turn on 15 digit display
format longformat long
x = [0.1, 0.01, 0.001];
y = sin(x)./x
% These values illustrate the fact that the limit of
% sin(x)/x as x approaches 0 is 1.
echo off
>> task1
If you use echo on in a script M-file, then MATLAB will also echo the comments, so they will appear in the Command Window.
74Introduction to MatlabIntroduction to Matlab
7 F ti M fil7. Functions M-files
•Functions are m-files that can be used to extend the MATLAB language.
F i i d d•Functions can accept input arguments and produce output arguments.
•Many of MATLAB’s own commands are implemented as m-files;
Try typing >> type mean to see how MATLAB calculates the mean.Try typing type mean to see how MATLAB calculates the mean.
•Functions use variables that are local to themselves and do not appear
in the main workspace.
•Always the m-file has the name of the function
Syntax: function [u,v,…]=FunctionName(x,y,…)
output input
75Introduction to MatlabIntroduction to Matlab
A l f f i
function x = quadratic(a,b,c)
An example of a function:
inputoutput
% QUADRATIC Find roots of a quadratic equation.%% X = QUADRATIC(A,B,C) returns the two roots of the% d ti ti A* ^2 + B* + Cn
taries
% quadratic equation y = A*x^2 + B*x + C.%% The roots are contained in X = [X1 X2].
Com
men
% S. MZIOU, October 2007
delta = 4*a*c;denom = 2*a;n
s denom = 2*a;rootdisc = sqrt(b.^2 - delta); % Root of the discriminantx1 = (-b + rootdisc)./denom;x2 = (-b - rootdisc)./denom;st
ruct
ion
x = [x1 x2];In
76Introduction to MatlabIntroduction to Matlab
Function m-files must start with the word function, followed by theoutput variable(s), an equals sign, the name of the function, and theinput variable(s).
Functions do not have to have input or output arguments. If there ismore than one input or output argument they must be separated bymore than one input or output argument, they must be separated bycommas. If there are one or more input arguments, they must beenclosed in round brackets, and if there are two or more outputarguments, they must be enclosed in square brackets. The followingillustrate these points (they are all valid function definition lines):
f1. function [xx,yy,zz] = sphere(n)
2. function fancyplot
3. function a = lists(x,y,z,t)3. function a lists(x,y,z,t)
77Introduction to MatlabIntroduction to Matlab
Function names must follow the same rules as variable names.
The file name is the function name with “.m” appended.
If the file name and the function name are different, MATLAB uses the
file name and ignores the function name file name and ignores the function name.
You should use the same name for both the function and the file to avoid
confusion.
Following the function definition line you should put comment lines
that explain how to use the function. These comment lines are printed in
th d i d h t h l f ll d b th fil the command window when you type help followed by the m-file name
at the prompt:
78Introduction to MatlabIntroduction to Matlab
>> help quadratic
QUADRATIC Find roots of a quadratic equationQUADRATIC Find roots of a quadratic equation.X = QUADRATIC(A,B,C) returns the two roots of the quadratic equationy = A*x^2 + B*x + C.The roots are contained in X = [X1 X2]
MATLAB only echoes the comment lines that are contiguous; the firstno comment line, in this case the blank line before the signature, tellsMATLAB that the help comments have ended. The first line of the helpcomments is searched and if successful displayed when you type acomments is searched and, if successful, displayed when you type alookfor command.
Comment lines can appear anywhere in the body of an m-file.Comments can be put at the end of a line of code: For instance
rootdisc = sqrt(b.^2 - delta); % Root of the discriminant
Blank lines can appear anywhere in the body of an m-file Apart fromBlank lines can appear anywhere in the body of an m-file. Apart fromending the help comment lines in a function, blank lines are ignored.
79Introduction to MatlabIntroduction to Matlab
d l f ( )/ h b f l lwe computed some values of sin(x)/x with x = 10−b for several values of b. Suppose, in addition, that you want to find the smallest value of b for which sin(10−b)/(10−b) and 1 agree to 15 digits. Here is a function M-file called sinelimit.m designed to solve that problem:M file called sinelimit.m designed to solve that problem:
function y = sinelimit(c)% SINELIMIT computes sin(x)/x for x = 10ˆ(-b),% h b 1 % where b = 1, ..., c.format longb = 1:c;x = 10.ˆ(-b);( );y = (sin(x)./x)’;
80Introduction to MatlabIntroduction to Matlab
8. Flow Control
MATLAB has four kinds of statements you can use to control the flowthrough your code:
If, else, elseif, end : execute statements based on a logical test
Switch, case, otherwise, end: execute groups of statements based
on a logical test
While, end: execute statements an indefinite number of times, based
l i l t ton a logical test
For, end: execute statements a fixed number of times
81Introduction to MatlabIntroduction to Matlab
If, Else, Elseif, end
The general form is:
The basic form is
if testStatements
if test1Statements1
elseif test2statements2Statements
endstatements2
elsedefault statements
end
The test is an expression that is either 1 (true) or 0 (false). Thestatements between the if and end statements are executed if the test istrue. If the test is false the statements will be ignored and execution willresume at the line after the end statement. The test expression can be avector or matrix, in which case all the elements must be equal to 1 forthe statements to be executed. Further tests can be made using theelseif and else statementselseif and else statements.
82Introduction to MatlabIntroduction to Matlab
Examples
If (x>=0)z=x;
Elsez=-x
83Introduction to MatlabIntroduction to Matlab
Switch
The basic form of a switch statement is:The basic form of a switch statement is:switch testcase result1
statementscase result2
statements. The respective statements are executed if the
value of test is equal to the respective results...otherwise
statementsd
q pIf none of the cases are true, the otherwisestatements are done. Only the first matchingcase is carried out. If you want the samestatements to be done for different cases youend statements to be done for different cases, youcan enclose the several results in curlybrackets:
84Introduction to MatlabIntroduction to Matlab
Example:
switch xcase 1disp(’x is 1’)case {2 3 4}case {2,3,4}disp(’x is 2, 3 or 4’)case 5disp(’x is 5’)otherwisedisp(’x is not 1, 2, 3, 4 or 5’)end
85Introduction to MatlabIntroduction to Matlab
While
The basic form of a while loop iswhile test
statementsend
The statements are executed repeatedly while the value of test isequal to 1. For example, to find the first integer n for which 1+2+…+nis greater than 1000:
n = 1;while sum(1:n)<=1000while sum(1:n)< 1000n = n+1;end
86Introduction to MatlabIntroduction to Matlab
For
The basic form of a for loop is:
for index = start:increment:stopstatements
endend
You can omit the increment, in which case an increment of 1 is assumed.ou ca o t t e c e e t, c case a c e e t o s assu edThe increment can be positive or negative. During the first pass throughthe loop the index will have the value start . The index will be increased by increment during each successive pass until the indexexceeds the value stop exceeds the value stop .
87Introduction to MatlabIntroduction to Matlab
The following example produces views of thepeaks function from many angles:
clfcolormap(gray)plotnum = 1;z = peaks(20);for az = 0:10:350subplot(6,6,plotnum)subplot(6,6,plotnum)surfl(z),shading flatview(az,30)axis tight
i ffaxis offplotnum = plotnum + 1;end
88Introduction to MatlabIntroduction to Matlab
Vectorised Code
MATLAB is a matrix language, and many of its algorithms are optimisedfor matrices. MATLAB code can often be accelerated by replacing forand while loops with operations on matrices.
In the following example, we calculate the factorial of the numbers from 1 to 500 using a for loop. Create a script m-file called factorialloop.mthat contains thefollowing code:
for number = 1:500fact = 1;fact 1;for i = 2:numberfact = fact*i;end( b ) f ty(number) = fact;
end
89Introduction to MatlabIntroduction to Matlab
We can time how long this program takes to run by using the stopwatchWe can time how long this program takes to run by using the stopwatchfunctions tic and toc:
>> tic;factorialloop;toc
elapsed_time =4.6332 Which is the time in seconds.
The same calculation can be done in much less time by replacing the internal for loop by the prod function. Create an m-file called factorialvect.m:
for number = 1:500y(number) = prod(1:number);
end
This version takes about a tenth of the time:
>> clear>> clear>> tic;factorialvect;tocelapsed_time =0.4331
90Introduction to MatlabIntroduction to Matlab
Further increases in speed can be achieved by pre-allocating the outputmatrix y. If we have an m-file called factorialpre.m:
y = zeros (1,500);for number = 1:500y(number) = prod(1:number);y(number) = prod(1:number);end
the execution time is about 10% faster:
>> clear>> tic;factorialpre;tocelapsed time =elapsed_time0.3752
91Introduction to MatlabIntroduction to Matlab
Graphics objects are the basic drawing elements used by MATLAB to
#. The notion of object
p j g ydisplay data. Each instance (figures, axis, lines, texts,…) of an object isassociated with a unique identifier called a handle. Using this handle, youcan manipulate the characteristics (called object properties) of anexisting graphics object You can also specify values for properties whenexisting graphics object. You can also specify values for properties whenyou create a graphics object.
•Two main functions
set: Find out about state of the objectt Ch th ti f th bj tget: Change the properties of the object
The basic syntax for setting the value of a property on an existing object is set(object_handle,'PropertyName','NewPropertyValue')
To query the current value of a specific object's property, use a statement like returned_value = get(object_handle,'PropertyName');
92Introduction to MatlabIntroduction to Matlab
•Three major object_handle
gcf : get current figuregca: get current axisgco: get current object
>> t=linspace(0,10,50)>> t linspace(0,10,50)>> plot(t,sint)
Assume that we want to plot the points themselves aswell as the line joining them.a) One solution is to clear the figure and to type thefollowing command:>> plot(t,sint,’-o’)
b) Another solution is to to handle all elements of the figure as objects>> h=get(gca,’children’)>> set(h,’marker’,’o’)