MATLAB MAS109 Week2
MATLAB MAS109 Week2
Jiseok Chae
MAS109 Week 2
1 Hello MATLAB!
2 Variables
Like today, every Friday with a recitation class, a video will be uploaded.
You should have already received a invitation email for MATLAB Grader.
Contents
1 Hello MATLAB!
2 Variables
If you start MATLAB you will see a window that looks something like this:
If you first launch MATLAB, the command window will look like:
>>
>> 2 + 3
>> 2 + 3
ans =
The command window contains both your input and MATLAB’s output.
In the slides we will distinguish them by highlighting the inputs by color.
There are several predefined functions and constants, not limited to below:
ans =
1.4142
>> log(exp(1))
ans =
pi is the constant π, sqrt is the square root, log is the natural log, and
exp is the base-e exponentiation.
Jiseok Chae (KAIST) Basics of MATLAB MAS109 Week 2 14 / 37
Hello MATLAB!
ans =
63
Contents
1 Hello MATLAB!
2 Variables
To declare a variable with the name x which contains the value 5, you
simply do the following.
>> x = 5
x =
The simple rule is that MATLAB evaulates the expression on the right
hand side, and stores it in the left hand side.
>> x = 5
x =
>> x = x + 17
x =
22
You can define variables with values derived from different variables.
>> hello KAIST = 142; welcome = 857;
>> neopjuk = hello KAIST + welcome
neopjuk =
999
>> welcome = 1;
>> neopjuk
neopjuk =
999
>> 40 + 1
ans =
41
ans =
11111
Contents
1 Hello MATLAB!
2 Variables
>> A = [1, 9, 7, 1; 2, 0, 2, 4]
A =
1 9 7 1
2 0 2 4
1 9 7 1
Now A contains the 2 × 4 matrix .
2 0 2 4
The same can be done as the following, in order to enhance the readability
of your input.
>> A = [1, 9, 7, 1;
2, 0, 2, 4]
A =
1 9 7 1
2 0 2 4
1
a contains the row vector 2 5 . b contains the column vector 0.
9
You can add, subtract, and multiply vectors and matrices with compatible
sizes using +, -, and *.
ans =
4
2
If you add the dot (.) in front of *, MATLAB computes the elementwise
product.
ans =
5 12
21 32
ans =
0.2000 0.3333
0.4286 0.5000
>> A .^ 2
ans =
1 4
9 16
ans =
1.0000 1.4142
1.7321 2.0000
ans =
1 3
2 4
ans =
>> b(3)
ans =
a(1) is the first entry of a, hence 2. b(3) is the third entry of b, hence 9.
Jiseok Chae (KAIST) Basics of MATLAB MAS109 Week 2 32 / 37
Matrices and Vectors
>> A = [1, 2, 3;
4, 5, 6;
7, 8, 9];
>> A(3, 2)
ans =
A(3, 2) means, select from A only the 3rd row and the 2nd column.
Therefore, A(3, 2) means the (3, 2) entry of A, which is A32 = 8.
Instead of specifying the index, a colon (:) can be used to say “select all”.
>> A = [1, 2, 3;
4, 5, 6;
7, 8, 9];
>> A(2, :)
ans =
4 5 6
A(2, :) means, select from A only the 2nd row and all the columns.
Therefore, A(2, :) is the 2nd row vector of A.
>> A = [1, 2, 3;
4, 5, 6;
7, 8, 9];
ans =
2
8
A([1, 3], 2) means, select from A only the 1st and 3rd row, and the
2nd column.
>> A = [1, 2, 3, 4;
5, 6, 7, 8;
9, 10, 11, 12];
ans =
10 11 12
Thank you!