Notes on using Matlab

advertisement
1
Simple Arithmetical Operations
Calculate the following:
(1)
(2)
(3)
(4)
tan(3 + 4 × 52 )
√
9
√
3
27
5
∑
i2
i=1
(5)
4!
(6)
(7)
π
e
2
variables
√
Variables can be used to store numeric values. For instance, you can store tan( 2) in x by entering:
>>x=tan(sqrt(2))
This variable can then be used on the right hand side of an equation such as:
>>fx=3+x^2
A variable can be overwritten.
>>x=x+1
Character strings can also be stored in variables. For example, to store the string And now for
something completely different in a variable, enter
>> str = And now for something completely different
3
3.1
(8)
3.2
Matrix Operations
Entering Matrix Explicitly
[
A= 1 2
]
3 ,
 
1
B = 2 ,
3

1
C = 0
0
0
1
0
Matrix Manipulation
Pick the (i,j)-th element of a matrix: C(i,j)
Find the size of a matrix: size(A)
Matrix addition, subtraction, multiplication, inverse.
1

0
0
1
>>A=2*eye(3)
>>B=ones(3)
>>A+B
>>A-B
>>A*B
>>A.*B
>>B^2
>>B.^2
To solve Ax = b:
>>A=rand(3);b=rand(3,1);
>>x1=inv(A)*b
>>x2=A\b
OLS estimate given dependent variable Y and explanatory variables X:
>>X=rand(20,3);Y=rand(20,1);b=(X’*X)\(X’*Y);
>>var(Y-X*b)
>>[mean(Y),std(Y)]
4
Programming
****This section is based on Mario Miranda’s tutorial of MATLAB.****
4.1
M-files
MATLAB is a powerful programming language as well as an interactive computational environment.
Files that contain code in the MATLAB language are called M-files. You create M-files using the
built-in Matlab text editor, save them, and later use them in your interactive sessions as you would
any other MATLAB function or command. There are two kinds of M-files:
• Scripts, which do not accept input arguments or return output arguments. They operate on
data in the workspace.
• Functions, which can accept input arguments and return output arguments. Internal variables
are local to the function.
If you are a new MATLAB programmer, just create the M-files that you want to try out and save
them to the current working directory. In the future, as you develop useful M-files of your own, you
will want to organize them into directories and personal toolboxes so that you can use them again
if needed.
4.2
Script File
Copy and paste the commands in ”command history” window and save it in MATLAB editor.
Then run it.
2
4.3
Function File
>>edit absolute
function [y,sign]=absolute(x)
if x>0
y=x;
sign=’+’;
else
y=-x;
sign=’-’;
end
The first line of a function M-file starts with the keyword function. It gives the function name
absolute, an input argument x, and two output argument, y the computed absolute value of x and
the sign of x.
Once you have created and saved the file, enter the following commands in the Matlab Command
Window
>>[y,sign]=absolute(-3)
4.4
For Loops
The for loop repeats a group of statements a fixed, predetermined number of times. A matching
end delineates the statements. Enter the following in the Command Window or a script file:
x = zeros(5,1);
for n = 1:5
x(n) = n^2;
end
x
For loops may be nested. For example,
H = zeros(4,4);
for i = 1:4
for j = 1:4
H(i,j) = i^j;
end
end
H
Exercise: Write a function with x and n as the input and calculates
4.5
If Statements
MATLAB offers six relational operators:
• < : less than
3
∑n
i=1
xi .
• ≤: less than or equal to
• > : greater than
• ≥ : greater than or equal to
• == : equal
• ̸= : not equal
and three logical operators:
• & : and
• | : or
• ∼ : not
which may be combined to produce logical statements, that is, statements that are either true or
false. Whenever MATLAB encounters a relational or logical operator, it produces a one if the
expression is true or a zero if the expression is false. Relational and logical operators are used
frequently with the if statement to control program execution.
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate groups
of statements. An end keyword, which matches the if, terminates the last group of statements.
x=2;
if x==1
disp(’x equals 1’)
else
disp(’x does not equal 1’)
end
Exercise: In matrix A = rand(5), find every element that is less than 0.5 (i.e. ai,j < 0.5),
replace it with -1 (i.e. a(i, j) = −1).
5
5.1
Graphics
Introduction
This tutorial describes basic Matlab graphics functions and provides examples of typical applications. In Matlab, only one plotting window or figure is open at any time. Plotting commands will
overwrite the current figure, allowing you to adjust its contents, until you request that new figure
be created
4
5.2
2-D Graphics
The Matlab plot command may be used to plot 2-dimensional figures with one or more overlays.
Try these examples. Be sure to follow along exactly, or you may not get the same results.
x = -pi:pi/100:pi;
y = sin(x);
plot(x,y);
title(’Sine Function’)
xlabel(’x’)
ylabel(’Sin(x)’)
legend(’Sin(x)’)
axis([-pi pi -1 1])
5.3
3-D Graphics
[x,y] = meshgrid(-8:.5:8);
r = sqrt(x.^2 + y.^2)+eps;
z = sin(r)./r;
mesh(x,y,z)
surf(x,y,z)
contour(x,y,z)
colorbar
5
Download