matlab seminar 2010
Post on 09-Apr-2018
214 Views
Preview:
TRANSCRIPT
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 1/46
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 2/46
What is MATLAB ?
MATrix LABoratory
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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 3/46
Characteristics of MATLAB
Programming language based (principally) on matrices .
± Slow - an interpreted language ,i.e .not pre-compiled.Avoid for loops; instead use vector form whenever
possible .
± Automatic memory management, i.e., you don't haveto declare arrays 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 .
Many application-specific toolboxes available .
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 4/46
Start menu Matlab MATLAB
³>>´ ±
>> date
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 5/46
Getting Help
>> help date
>> helpwin date
helpwin gives you the same information as help, but in a different window.
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 6/46
Getting Help
>> doc date
>> lookfor date % search for keywords that best describe the function
>>Ctrl+C% stop Matlab from running
>> clc % clear screen
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 7/46
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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 8/46
Creating Variables
Matlab as a calculator:
>>2+5
>>7*10+8
>>5^2
µans¶ - "answer", used in MATLAB as the default variable.
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 9/46
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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 10/46
Listing & Clearing Variables
>> whos
>> clear, clear all %clear variables from memory
>> a=10
>> b = 20
>> the_average = (a + b ) / 2
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 11/46
Creating vectors
Row separator:
space/coma (,)
Creating sequences:
From : jump: till
linespec(X1, X2, N)
generates N points between
X1 and X2.
Coulmn separator:
Semicolon (;)
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 12/46
Creating Matrices
Matrices must be rectangular.
Creating random matrices:
2-by-4 random matrix
(2 rows and 4 columns).
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 13/46
Creating Matrices
You can combine existing vectors as matrix elements:
You can combine existing matrices as matrix elements:
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 14/46
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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 15/46
Linear Algebra Operations
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 16/46
Matrix Multiplication
Inner dimensions must be equal
Dimension of resulting matrix = outermost
dimensions of multiplied matrices
Resulting e
lements = dot product of the rows of
the 1st matrix with the columns of the 2nd matrix
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 17/46
Type the following:
>>a=[2 3]
>>b=[3 2]
>>a*b
>>a.*b
>>a.*b¶
>>a*b¶
Vector Multiplication
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 18/46
String Arrays
Created using single quote delimiter (')
Indexing is the same as for numeric arrays
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 19/46
String Array Concatenation
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 20/46
Working with String Arrays
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 21/46
Example: Solving Equations
Solve this set of simultaneous equations: Ax=B, x=?
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 22/46
Cr eating Scr ipts with MATLABCr eating Scr ipts with MATLAB
Editor/Debugger Editor/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:
>> editRun
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 23/46
Add path Add path
>> addpath C:\EMEM899\Somedirectory
Set path
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 24/46
Scr ipt M Scr ipt M--files 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 % Exit current function% Return to invoking function/command line.
Continue % go to next iteration
Input % Prompt for user input
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 25/46
A Simple Scr ipt A Simple Scr ipt
% 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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 26/46
Running Scr ipts Running Scr ipts
>> 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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 27/46
Find and Replace ± ctrl+F
Key words
Wrong use of key words
Indenting: Ctrl+I
Running Scr ipts ( Running Scr ipts (22) )
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 28/46
F low C ont r ol C onst r ucts F low C ont r ol C onst r ucts
Logic Control:
± IF / ELSEIF / ELSE
± SWITCH / CASE / OTHERWISE
Iterative Loops:
± FOR
± WHILE
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 29/46
The if, elseif and else statementsThe if, elseif and else 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 END, while ELSE IFdoes.
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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 30/46
Boolean Operators & Indexing
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 31/46
Switch, C ase, and Other wiseSwitch, C ase, and Other wise
switch input_num
case -1input_str = 'minus one';
case 0
input_str = 'zero';
case 1
input_str = 'plus one';
case {-10,10}
input_str = '+/- ten';
otherwise
input_str = 'other value';
end
More efficient than elseif statements
Only the first matching case is executed
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 32/46
P r oblem P r oblem
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
Write a comment for error case.
Save the file under units.m
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 33/46
SolutionSolution
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;
disp ([num2str(x) ' in ' units ' convertedto cm is :' num2str(y)])
case {'cm','centimeter'}y = x
otherwise
disp (['unknown units:' units])y = nan;
end
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 34/46
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 loopThe for loop
N=10;
for I = 1:2:N
for J = 1:N A(I,J) = 1/(I+J-1);
end
end
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 35/46
The while loopThe 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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 36/46
Array Operations
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 37/46
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(1),Y(1)), (X(2),Y(2)), (X(3),Y(3)), etc.,
and then connect all these points together with line.
E
xample:
>> x=1:1:5;
>>Y=[2 7 0 -8 6];
>> plot (x,y);
>> xlabel (µlabel for x-axis¶)
>> ylabel (µlabel for y-axis¶) >> title (µtitle¶)
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 38/46
C
heck the foll
owing: x_points = [-10 : .05 : 10];
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 ('1', '2', '3', '4')
Multiple Plots
- 10 -5 0 5 10 0
0. 5
1
1. 5
2
2. 5 x 10
4
x-axis
y - a x i s
Comp aring E xponential Func tions
1
2
3
4
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 39/46
Subplots
multiple plots in the same window, each with their own
axes.
Subplot (M,N,P)
M ± rows N - columns
P ± number of subplot
in the figure
Subplot (2,2,1)
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 40/46
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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 41/46
Special Graph Annotations (TeX)
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 42/46
Plot Editor Toolbar
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 43/46
Exercise
x = (1, 1.05, 1.1, 1.15« 5)
Y=sin(x)
Z=log(x)
Put your name in the title
Hint: check the doc on function ³LineSpec .́
Create the following:
1 1.5 2 2 .5 3 3 .5 4 4 .5 5 -1
-0.5
0
0 .5
1
1 .5
2Merav's graph
x
y
sin(x)
log(x)
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 44/46
Solution
x=1:0.05:5;
y=sin(x);
z=log(x);
hold on plot (x,y,'-.r*')
plot (x,z,'-.go')
hold off
title ('Merav''s graph');
xlabel ('x')
ylabel ('y')
legend ('sin(x)', 'log(x)');
8/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 45/46
More exercise
Make a 3 three-dimensional graph of (x,y,z) ± use Matlab help.
Make two separate 2-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
1s in(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/8/2019 Matlab Seminar 2010
http://slidepdf.com/reader/full/matlab-seminar-2010 46/46
Solution
3-D graph:
>> plot3(x,y,z)
>> grid
>> xlabel ('x')
>> ylabel('y')
>> zlabel('z')
>> title ('3D graph')
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'
);
top related