matlab seminar
TRANSCRIPT
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 1/70
A Seminar On
MATLABThe Language of Technical
Computing
By
Pratik Kamat
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 2/70
WHAT IS MATLAB ?
´ MAT-rix LAB-oratory
´ Developed by The Mathworks, Inc (http://www.mathworks.com))
´ Interactive, integrated, environment
« for numerical computations
« for symbolic computations
« for scientific visualizations
´ It is a high-level programming language
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 3/70
CHARACTERISTICS OF MATLAB
´ Programming language based (principally) on matrices
« Automatic memory management, i.e., you don't have to declarearrays in advance
« Intuitive, easy to use
« Shorter program development time than traditional programming languages such as Fortran and C
« Can be converted into C code via MATLAB compiler for better efficiency
« Slow - an interpreted language ,i.e. .not pre-compiled. Avoid for loops; instead use vector form whenever possible
´ Many application-specific toolboxes available
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 4/70
STARTING MATLAB
Start menu Matlab MATLAB
>> date
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 5/70
GETTING HELP
>> help date
>> helpwin date
helpwin gives you the same information as help, but in a different window.
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 6/70
GETTING HELP (CONTD.)
>> doc date
>> lookfor date % search for keywords that best describe the function
>> Ctrl+C % stop Matlab from running
>> clc % clear screen
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 7/70
SPECIAL CHARACTERS
´ >> % default command prompt
´ % % comment - MATLAB simply ignores anything to the right of this
sign (till the end of the line).
>> % my comment
´ ; % semicolon at the end of the line will prevent MATLAB from
echoing the information you type on the screen.
>> a=20
>> B=20;
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 8/70
CREATING VARIABLES
´ Matlab as a calculator:
´ >>2+5
´ >>7*10+8
´ >>5^2
´
µans¶ - "answer", used in MATLAB as the default variable.
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 9/70
DEFINING YOUR OWN VARIABLES
� When Matlab comes across a new variable name - it automatically creates
it.
� Begins with a LETTER, e.g., A2z.
� Can be a mix of letters, digits, and underscores (e.g., vector_A, but not
vector-A)� Not longer than 31 characters.
� No spaces
� Different mixes of capital and small letters = different variables.
For example: "A_VaRIAbLe", "a_variable", "A_VARIABLE", and
"A_variablE
� >> String=µthis is a string¶
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 10/70
TAKING USER DEFINED INPUTS
� Matlab uses the function µinput¶ to accept user-defined inputs
� E.g. y=input(µEnter any Value¶);
Now, if a user has to enter a Vector,then he enters[ 1 2 4 5]
For a matrix, the syntax is as follows
[1 2 3 4 5 ; 9 8 7 6 5]
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 11/70
PRACTICE PROBLEM
Write a Program to accept the length of side of a square and
display its area.
Write a Program to accept three numbers from the user and todisplay their average.
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 12/70
SOLUTION
x=input(¶Enter the first number·);
y=input(¶Enter the second number·);
z=input(¶Enter the third number·);
Average=(x+y+z)/3;
side=input(¶Enter the length of the side·);
Area=side*side;
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 13/70
LISTING & CLEARING VARIABLES
>> whos
>> clear, clear all %clear variables from memory
>> clc %clears the screen
>> a=10
>> b = 20
>> the_average = (a + b ) / 2
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 14/70
CREATING VECTORS
R ow separator:
space/coma (,)
Creating sequences:
� From : jump: till
� linespec(X1, X2, N)
generates N points between
X1 and X2.
Coulmn separator:Semicolon (;)
Indexing Begins at 1
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 15/70
CREATING MATRICES
� Matrices must be rectangular.
� Creating random matrices:
2-by-4 random matrix
(2 rows and 4 columns).
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 16/70
CREATING MATRICES (CONT.D)
� You can combine existing vectors as matrix elements:
� You can combine existing matrices as matrix elements:
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 17/70
INDEXING INTO A MATRIX
>> B=A(3,1);
>> A(:,end)=[1;7;3;8;4];
� The row number is first, followed by the column number.
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 18/70
PRACTICE PROBLEM
Write a Program to accept three numbers from the user and to
display their average.
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 19/70
SOLUTION
x i t(¶ t r t rs·);
v r g (x(1) x(2) x( ))/l gt (x)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 20/70
LI LGEBRA ERATI
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 21/70
MATRIX MULTIPLICATION
´ Inner dimensions must be equal
´ Dimension of resulting matrix = outermost
dimensions of multiplied matrices
´
Resulting elements = dot product of the rows of the st matrix with the columns of the nd matrix
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 22/70
VECTOR MULTIPLICATION
Type the following:
>>a=[2 3]
>>b=[3 2]
>>a*b
>>a.*b
>>a.*b¶
>>a*b¶
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 23/70
PRACTICE PROBLEM
Write a Program to display the squares of all numbers from 1 - 20
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 24/70
SOLUTION
X=1:1:10;
sq=X.*X
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 25/70
STRING ARRAYS
´ Created using single quote delimiter (')
� Indexing is the same as for numeric arrays
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 26/70
STRING ARRAY CONCATENATION
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 27/70
WORKING WITH STRING ARRAYS
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 28/70
EXAMPLE: SOLVING EQUATIONS
´ Solve this set of simultaneous equations:
Ax=B, x=?
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 29/70
EXAMPLE: SOLVING EQUATIONS
´ Solve this set of simultaneous equations:
Ax=B, x=?
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 30/70
MATLAB DEBUGGER
´ Automatically saves files as ASCII text files for you.
´ Scripts in MATLAB has the ".m" suffix.
´ They are also called "M-files".
Open Matlab Editor:
´ File New M-file OR :
´ >> edit
Run
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 31/70
FLOW CONTROL CONSTRUCTS
´Logic Control:
«IF / ELSEIF / ELSE
«SWITCH / CASE / OTHERWISE
´Iterative Loops:
«FOR
«WHILE
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 32/70
THE IF,THE IF, ELSEIF ELSEIF AND ELSE AND ELSE STATEMENTS STATEMENTS
if I == J
A(I,J) = 2;
elseif abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end
� Works on Conditional statements
� Logic condition is µtrue¶ if its different then 0.
� ELSEIF does not need a matching E ND, while ELSE IF does.
if I == J
A(I,J) = 2;
else if abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end %else if
end %if
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 33/70
BOOLEAN OPERATORS & INDEXING
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 34/70
SWITCH, CASE, AND OTHERWISE SWITCH, CASE, AND OTHERWISE
switch input_num
case -1input_str = 'minus one';
case 0input_str = 'zero';
case 1input_str = 'plus one';
case {-10,10}input_str = '+/- ten';
otherwiseinput_str = 'other value';
end
´More efficient than elseif statements
´Only the first matching case is executed
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 35/70
P ROBLEM P ROBLEM
´ Build a program which receives a variable x and its units (mm, cm, inch, meter)
and calculates Y- it¶s value in centimeters units.
´ Use switch case.
´ 1 Inch = 2.54 cm
´ Save the file under units.m
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 36/70
SOLUTION SOLUTION
x = 3.0;
units = 'mm';
switch units
case {'in','inch'}
y = 2.54*x % converts to centimeters
case {'m','meter'}y = x*100 % converts to centimeters
case { 'millimeter','mm'}y = x/10;
case {'cm','centimeter'}y = x ;
otherwise
disp (['unknown units:' units])
End
y
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 37/70
� Similar to other programming languages
� Repeats loop a set number of times (based on index)
� Can be nested
� Each loop is closed with end.
THE FOR LOOP THE FOR LOOP
N=10;
for I = 1:2:N
for J = 1:N A(I,J) = 1/(I+J-1);
end
end
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 38/70
P ROBLEM P ROBLEM
´ Build a program to generate the factorial of a number.
´ Use for loop
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 39/70
SOLUTION SOLUTION
n=5;
facto=1;
for i=1:n
facto=facto*n;
end
facto
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 40/70
THE WHILE LOOP THE WHILE LOOP
I=1; N=10;
while I<=N
J =1;
while J<=N
A(I,J)=1/(I+J-1);J =J+1;
end
I=I+1;
end
� Similar to other programming languages
� Repeats loop until logical condition returns FALSE.
� Can be nested.
� Stopping infinity loop:
Ctrl+C
Ctrl+break
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 41/70
ARRAY OPERATIONS
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 42/70
LINE PLOTS IN TWO
DIMENSIONS´ Plot (x,y)
´ makes a two-dimensional line plot for each point in X and its
corresponding point in Y: (X( ),Y( )), (X( ),Y( )), (X(3),Y(3)), etc., and
then connect all these points together with line.
´ Example:
´ >> x= : :5;
´ >>Y=[ 7 0 -8 6];
´ >> plot (x,y);
´ >> xlabel (¶label for x-axis·)
´ >> ylabel (¶label for y-axis·)
´ >> title (¶title·)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 43/70
MULTIPLE PLOTS´ C
heck the following:´ x_points = [- 0 : .05 : 0];
´ plot(x_points, exp(x_points)); % plot in Blue (default)
´ grid on
´ hold on
´ plot(x_points, exp(.95 .* x_points), 'm');% plot in Magenta
´ plot(x_points, exp(.85 .* x_points), 'g'); % plot in Green
´ plot(x_points, exp(.75 .* x_points), 'p'); % plot a star
´ hold off
´ xlabel('x-axis'); ylabel('y-axis');
´ title('Comparing Exponential Functions');
´ legend (' ', ' ', '3', '4')
- 10 -5 0 5 10 0
0. 5
1
1. 5
2
2. 5 x 10
4
x-axis
y - a x i s
Comparing E xponential Functions
1
2
3
4
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 44/70
SUBPLOTS
´Multiple plots in the same window, each
with their own axes.
´ Subplot (M,N,P)´M ² rows
´ N - columns
´ P ² number of subplotin the figure
Subplot (2,2,1)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 45/70
MORE ABOUT FIGURES
´ Figure % Open a new figure without closing old
figures
´ Figure (i) % Open the i-th figure
´ Close all % close all open figures
´ axis ([xmin xmax ymin ymax]) % sets scaling for
the x- and y-axes on the current plot.
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 46/70
SPECIAL GRAPH ANNOTATIONS (TEX)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 47/70
PLOT EDITOR TOOLBAR
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 48/70
EXERCISE
´ x (1, 1. , 1.1, 1.1 « )
´ si (x)
´ Z l g(x)
´ P t y r i t titl
´ Hi t: c c t c f cti ´Li S cµ.
Create the following:
1 1 .
¡ ¡ .
¢ ¢ .
£ £ .
¤ 1
-0 .
0
0 .
1
1 .
¡
M ¥
r ¦
v' §
̈ r
¦
©
h
§ i
(
)
l ̈ (
)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 49/70
SOLUTION
x= :0.05:5;
y=sin(x);
z=log(x);
hold onplot (x,y,'-.r*')
plot (x,z,'-.go')
hold off
title ( ep's graph');
xlabel ('x')
ylabel ('y')
legend ('sin(x)', 'log(x)');
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 50/70
EXERCISE
Plot the following graph:
y=1 for x>0
=-1 elsewhere
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 51/70
SOLUTION
x=-3:0.0 :3
for i= :length(x)
if x(i) > 0
y(i) = ;else
y(i) = - ;
end
end
plot(x,y)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 52/70
MORE EXERCISE
´ Make a 3 three-dimensional graph of (x,y,z) ² useMatlab help.
´ Make two separate -D graphs, with separate axis, in the same
window: y vs. x, and z vs. x.
´ Use the same x,y,z as defined in the previous exercise
1
2
3
4
5
-1
-0.5
0
0. 5
10
0. 5
1
1. 5
2
x
3D graph
y
z
1 2 3 4 5 -1
-0.8
-0.6
-0.4
-0.2
0
0. 2
0. 4
0. 6
0. 8
1sin(x)
x
y = s i n ( x )
1 2 3 4 5 0
0. 2
0. 4
0. 6
0. 8
1
1. 2
1. 4
1. 6
1. 8
x
log(x)
z
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 53/70
SOLUTION
´ 3-D graph:
´ >> plot3(x,y,z)
´
>> grid´ >> xlabel ('x')
´ >> ylabel('y')
´ >> zlabel('z')
´ >> title ('3Dgraph')
� Subplots
>> subplot (1,2,1);
>> plot(x,y);
>> title ('sin(x)');>> xlabel('x');
>> ylabel('y=sin(x)');
>> grid;
>> subplot (1,2,2);
>> plot(x,z);>> xlabel('x');
>> title ('log(x)');
>> grid;
>> ylabel ('z');
GRAPHICAL USER INTERFACE
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 54/70
GRAPHICAL USER INTERFACE
DEVELOPMENT ENVIRONMENT (GUIDE)
´ Graphical User Interface Design Environment provides a set of tools for creating graphical user interfaces (GUIs).
´ GUIDE automatically generates an M-file that controls how the GUI
operates.
´ StartingGUIDE:
>> guide Push
buttons
Static
text
Pop-up menu
axes
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 55/70
GUIDE TOOLS ± THE LAYOUT
EDITOR
� In the Quick Start dialog, select the Blank GUI (Default) template
� Display names of components: File preferences Show names in component palette
� Lay out your GUI by dragging components
(panels, push buttons, pop-up menus, or axes)
from the component palette, into the layout area
Drag to
resize
Component
panel
Layout area
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 56/70
USING THE PROPERTY INSPECTOR
� Labeling the Buttons
� Select Property Inspector from the View menu.
� Select button by clicking it.
� Fill the name in the String field.
Activate
GUI
Property
Inspector
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 57/70
PROGRAMMING A GUI
´ Callbacks are functions that execute in response to some action bythe user.
´ A typical action is clicking a push button.
´ You program the GUI by coding one or more callbacks for each of its
components.
´ A GUI's callbacks are found in an M-file that GUIDE generatesautomatically.
´ Callback template for a push button:
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 58/70
HANDLES STRUCTURE
´ Save the objects handles: handles.objectname
´ Save global data ± can be used outside the function.
´ Example: popup menu:
´ Value ± user choice of the popup menu
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 59/70
HANDLES STRUCTURE(CONTD.)
´ Use ´strµ as the string pointer
´ Static Text
« set(handles.text ,·String·,str)
´ Radio Button
« set(handles.radiobutton,·Value·,0)
´ Pop-Up Menu
« get(handles.radiobutton,·Value·)
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 60/70
SCRIPT M-FILES
´Standard ASCII text files´Contain a series of MATLAB expressions
´A script does not define a new workspace
% Comments start with "%" character
pause % Suspend execution - hit any key to continue.
keyboard % Pause & return control to command line.
% Type "return" to continue.
break % Terminate execution of current loop/file.
return%
Ex
it current function% Return to invoking function/command line.
Continue % go to next iteration
Input % Prompt for user input
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 61/70
A SIMPLE SCRIPTS
% a simple MATLAB m-file to calculate the
% square root of an input numbers.
my_num=input('insert a number');% now calculate the square root of the number and print
it out:
square_root = sqrt(my_num)
Write a program which receives a number from the user,calculates it¶s square root (use µsqrt¶ command) and displays
the result.
save the script as "square_root_script.m" in your own folder
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 62/70
RUNNING SCRIPTS
´ >> square_root_script
´ The header - comments you place at the beginning of your scripts will bereturned to users when they get help for your script.
´ >> help square_root_script
´ Note: The variables defined in the script remain in the workspace even
after the script finishes running.´ Creating comments: ctrl+r, or right click on the mouse, or
%{
coment
coment
%}
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 63/70
RUNNING SCRIPTS (CONTD.)
´ Find and Replace ± ctrl+F
´ Key words
´ Wrong use of key words
´ Indenting: Ctrl+I
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 64/70
FUNCTIONS
´ Functions describe subprograms
«Take inputs, generate outputs
«Have local variables (invisible in global workspace)
´Core MATLAB (Built-in) Functions«sin, abs, exp, ...
Can¶t be displayed on screen
´MATLAB-supplied M-file Functions
«mean, linspace, «
Ca be displayed on screen
´ User-created M-file Functions
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 65/70
STRUCTURE OF A FUNCTION FILE
function y = mean(x)
% ME AN Average or mean value.
% For vectors, ME AN(x) returns the mean value.
% For matrices, ME AN(x) is a ro w vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
m = n;
end
y = sum (x)/ m ;
Keyword: function Function Name (same as file name .m)
Output Argument(s) Input Argument(s)
Online Help
MATLABCode
»
output_ value
=mean
(input_
value)
Command Line Syntax
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 66/70
MULTIPLE INPUT AND OUTPUT
ARGUMENTS
function r = ourrank(X,tol)% OURRANK Rank of a matrix
s = svd (X);if (nargin == 1)
tol =
max(size
(X))*s
(1)*eps
;
end
r = sum (s > tol); function [mean,stdev] = ourstat(x)
% OURSTAT Mean & std. deviation
[m,n] = size(x);
if m == 1
m = n;end
mean = sum (x)/ m ;
stdev = sqrt(sum (x.^2)/ m ± mean.^2);
Multiple Input
Arguments ( , )
Multiple Output
Arguments [ , ]
» R ANK = ourrank(rand (5),0.1);
» [ME AN,STDEV] = ourstat(1:99);
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 67/70
MATLAB CALLING PROPERTY
High
variable
built-in function
subfunctionprivate function
MEX-file
P-file
M-file
Low
» cos='This string.';
» cos(8)
ans=
r
» clear cos
» cos(8)
ans =
-0.1455
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 68/70
MATLAB IN P UT MATLAB IN P UT
To read files in
´ if the file is an ascii table, use ́ loadµ
´ if the file is ascii but not a table, file I /O needs
´fopenµ and ´fcloseµ
´ Reading in data from file using fopen dependson type of data (binary or text)
´ Default data type is ´binaryµ
´ Images can be opened using ´imshowµ and canbe read using ´imreadµ
ADD PATH TO RECOGNISE
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 69/70
ADD PATH TO RECOGNISE
WORKSPACE
´ >> addpath C:\Docu .\ Somedirectory
´ Set path
8/6/2019 Matlab Seminar
http://slidepdf.com/reader/full/matlab-seminar 70/70
THANK YOU