MIT15 075JF11 Tutorial
MIT15 075JF11 Tutorial
M$7/$% Desktop
The Command Window is where you type the commands or instructions into M$7/$%.
The Command History contains a record of all the commands entered in the Command Window.
The Workspace is where your data is stored in M$7/$% during the current session.
M$7/$B Fundamentals
MATLAB can be used as a calculator performing simple and complex calculations.
>> t = 2;
>> x = sin(3*t+pi/2)^2
x=
0.9219
MATLAB saves data in variables. You can think of MATLAB variables as data containers.
All variables are arrays. Even scalar variables are treated as 1x1 arrays.
>> x = 1:2:11
x=
1 3 5 7 9 11
>> x = linspace(1,11,6)
x=
1 3 5 7 9 11
To transpose it
>> x =x'
x=
1
3
5
7
9
11
>> size(x)
ans =
6 1
>> t = 0:0.01:100;
To create matrices
A=
1 2 3
4 5 6
7 8 9
>> ones(2)
ans =
1 1
1 1
>> zeros(3,2)
ans =
0 0
0 0
0 0
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
To concatenate matrices
>> A =
1 2 3
4 5 6
7 8 9
>> B = [A A]
B=
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
>> B = A + 2
B=
3 4 5
6 7 8
9 10 11
>> B = 3*A
B=
3 6 9
12 15 18
21 24 27
Writing Functions
If-Elseif-Else
While. Run multiple iterations of an operation until a condition is no valid
For. Repeat an operation for a known number of iterations.
x = 0;
for i=1:10
x = x+i;
end
z = 1:10;
x = sum(z)
>> v = 1:20;
>> vsample10 = randsample(v,10)
vsample10 =
14 4 16 17 12 15 20 10 11 3
>> mean(vsample10)
ans =
12.2000
>> std(vsample10)
ans =
5.4528
>> quantile(vsample10,0.5)
ans =
13
>> median(vsample10)
ans =
13
Let’s generate ten random numbers from the normal distribution, say with mean 5 and variance 4.
>>r =5 + 2.*randn(10,1)
>> normcdf(5,5,2)
ans =
0.5000
There are several related functions for other probability distributions, for example:
Binomial – binornd, binopdf
Poisson – poissrnd, poisspdf
Uniform – unifrnd, unifpdf
Gamma – exprnd, exppdf
Help
There may be times when you forget how to use a certain function, even though you remember
the function’s name. In this case, simply type help function_name
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.