Save

advertisement
Introduction to Matlab
1
What is Matlab?
•
•
•
Matlab is basically a high level language which has many specialized
toolboxes for making things easier for us
MATLAB is a high-level language and interactive environment that
enables us to perform computationally intensive tasks faster than with
traditional programming languages such as C, C++, and Fortran.
How high?
Matlab
High Level
Languages such as
C, Pascal etc.
Assembly
2
Matlab Desktop
Launch Pad
Command
Window
History
3
Matlab Desktop – cont’d
Workspace
Command
Window
Current
DIrectory
4
Matlab Help
5
Matlab Programs
• Matlab is an extravagant calculator if all we can do is
execute commands typed into the Command Window…
• So how can we execute a “program?”
• Programs in Matlab are:
– Scripts, or
– Functions
• Scripts: Matlab statements that are fed from a file into the
Command Window and executed immediately
• Functions: Program modules that are passed data
(arguments) and return a result (i.e., sin(x))
• These can be created in any text editor (but Matlab
supplies a nice built-in editor)
6
Matlab Editor
Access to
commands
Color keyed
text with auto
indents
tabbed sheets for other
files being edited
7
The Matlab Environment
• Matlab is an interpreted language
– Commands are typed into the COMMAND Window and executed
immediately
– Variables are allocated in memory as soon as they are first used in
an expression
– Commands must be re-entered to be re-executed
• All variables created in the Command Window are in what is called
the Base Workspace
– Variables can be reassigned new values as needed
– Variables can be selectively cleared from the workspace
• The Workspace can be saved to a data file
– File extension is .mat (ex: mydata.mat)
– File is in binary and essentially unreadable by humans
– .mat files can be reloaded back into the Matlab Workspace
8
Reserved Words…
• Matlab has some special (reserved) words that you may
not use…
for
end
if
while
function
return
elseif
case
otherwise
9
switch
continue
else
try
catch
global
persistent
break
Variables
•
No need for types. i.e.,
•
int a;
double b;
float c; are created with double precision unless specified
All variables
and they are matrices.
•
10
Example:
>>x=5;
After these
statements, the variables are 1x1 matrices with double
>>x1=2;
precision
Array, Matrix
•
a vector
x = [1 2 5 1]
x =
1
•
5
a matrix
x =
1
•
2
2
5
3
transpose
1
x = [1 2 3; 5 1 4; 3 2 -1]
3
1
2
4
-1
y = x’
y =
1
2
5
1
11
Long Array, Matrix
•
t =1:10
t =
1
2
3
4
k =2:-0.5:-1
•
5
6
7
8
k =
2
•
1.5
1
0.5
0
-0.5
B = [1:4; 5:8]
x =
1
5
12
2
6
3
7
4
8
-1
9
10
Generating Vectors from functions
•
zeros(M,N)
MxN matrix of zeros
x = zeros(1,3)
x =
0
0
0
•
ones(M,N)
MxN matrix of ones
x = ones(1,3)
x =
1
1
1
•
rand(M,N)
13
MxN matrix of uniformly
distributed random
numbers on (0,1)
x = rand(1,3)
x =
0.9501 0.2311 0.6068
Matrix Index
•
•
The matrix indices begin from 1 (not 0 (as in C))
The matrix indices must be positive integer
Given:
A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or logicals.
A(4,2)
Error: ??? Index exceeds matrix dimensions.
14
Concatenation of Matrices
•
x = [1 2], y = [4 5], z=[ 0 0]
A = [ x y]
1
2
4
5
B = [x ; y]
1 2
4 5
C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
15
Operators (arithmetic)
+
*
/
^
‘
16
addition
subtraction
multiplication
division
power
complex conjugate transpose
Matrices Operations
Given A and B:
Addition
17
Subtraction
Product
Transpose
Operators (Element by Element)
.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
18
The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1
x = A(1,:)
x=
c=x./y
d = x .^2
b=
c=
0.33 0.5 -3
d=
y = A(3 ,:)
y=
1 2 3
b = x .* y
3 8 -3
3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
19
1
4
9
Basic Task: Plot the function sin(x) between
0≤x≤4π
• Create an x-array of 100 samples between 0 and 4π.
• Calculate sin(.) of the x-array
>>x=linspace(0,4*pi,100);
• Plot the y-array
1
0.8
0.6
>>y=sin(x);
0.4
0.2
0
-0.2
-0.4
>>plot(y)
-0.6
-0.8
-1
20
0
10
20
30
40
50
60
70
80
90
100
Display Facilities
0.7
0.6
• plot(.)
0.5
0.4
0.3
Example:
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
>>plot(x,y)
0.2
0.1
0
-0.1
-0.2
-0.3
0
10
20
30
40
50
60
70
80
90
100
0
10
20
30
40
50
60
70
80
90
100
0.7
0.6
• stem(.)
0.5
0.4
0.3
Example:
>>stem(y)
>>stem(x,y)
0.2
0.1
0
-0.1
-0.2
-0.3
21
Operators (relational, logical)
•
•
•
•
•
•
•
•
22
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
& And operator
| Or operator
Flow Control
•
•
•
•
•
23
if
for
while
break
….
Control Structures
• If Statement Syntax
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
24
Some Dummy Examples
if ((a>3) & (b==5))
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end
Control Structures
• For loop syntax
for i=Index_Array
Matlab Commands
end
Some Dummy Examples
for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
25
Control Structures
• While Loop Syntax
while (condition)
Matlab Commands
end
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
26
Use of M-File
Click to create
a new M-File
• Extension “.m”
• A text file containing script or function or program to run
27
Use of M-File
Save file as Denem430.m
If you include “;” at the
end of each statement,
result will not be shown
immediately
28
Notes:
• “%” is the neglect sign for Matlab (equaivalent of “//”
in C). Anything after it on the same line is neglected
by Matlab compiler.
• Sometimes slowing down the execution is done
deliberately for observation purposes. You can use
the command “pause” for this purpose
pause %wait until any key
pause(3) %wait 3 seconds
29
Programming tips and tricks
• Programming style has huge influence on program
speed!
•
slow.m
tic;
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
30
fast.m
tic
x=-250:0.1:250;
s=sqrt(x);
s(x<0)=0;
toc;
Loops are slow: Replace loops by vector operations!
Memory allocation takes a lot of time: Pre-allocate memory!
Use profile to find code bottlenecks!
.m files
• .m files are just
text files
• Do work in .m file
• Paste work into
Matlab prompt
• Use ; to end lines
• Save .m files
• Use % to add comments
31
Basic Operations
• Always use brackets [ ] to define matrices
• Always use prentices ( ) to call values of matrices
• The row is always first, the column is always second,
i.e. M1(3,2) is not the same as M1(2,3)
• To see which variables exist, use >>whos
• To delete variables, use >>clear x y
• To find out size use >>size(M1)
32
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
33
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)
34
References
• http://www.mathworks.com/products/matlab/index.html
• http://www.ccs.neu.edu/home/wmason/
• Mastering MATLAB 7. Duane C. Hanselman, Bruce L.
Littlefield. Prentice Hall, 2004.
• MATLAB: An Introduction with Applications. Amos Gilat.
Wiley, 2003.
35
Download