Introduction to Simulation: Beginner


Matrix Arithmetic


Now let's go through some basic arithmetic in MATLAB. First, we create simple matrices to work with.

A = [1 2; 3 4]
B = [5 6; 7 8]
C = [9 10; 11 12]

A =
   1   2
   3   4

B =
   5   6
   7   8

C =
    9   10
   11   12

Suppose we want to add two matrices, that's very simple.
A + B

ans =
    6    8
   10   12

Or subtract them.
A - B

ans =
  -4  -4
  -4  -4

Let's try to multiply them.
A * B

ans =
   19   22
   43   50

Here we need to note that this is pure matrix multiplication, which means that the inner dimensions of the matrices A and B have to match. For example, if we create another matrix that does not have the same number of rows as the number of columns in A it's not going to work.
B2 = [1 2; 4 5; 6 7];
size(B2)
size(A)

ans =
   3   2

ans =
   2   2

So, if we try to multiply them, we'll get an error message.
A * B2

error: operator *: nonconformant arguments (op1 is 2x2, op2 is 3x2)


Then, we can transpose B2.
A * B2'

ans =
    5   14   20
   11   32   46

In this case, the inner dimensions meet the requirement.



We can also divide matrices with a forward slash /. But if you remember from linear algebra there isn't really a matrix division like that. The division of scalars is very simple.

3/5

ans = 0.6000

The order of the operations and usage of parentheses does not contain any surprises.
There are also situations when we want to perform element-by-element operations. For that we need to put a dot before a multiply sign.
A .* B

ans =
    5   12
   21   32

So it multiplies each matrix element by each corresponding element in the other matrix. That also works for division, so, with dot slash.
A ./ B

ans =
   0.2000   0.3333
   0.4286   0.5000

Let's consider inner products in more detail.
x = [1 2 3]
y = [4 5 6]
x * y'

x =
   1   2   3

y =
   4   5   6

ans = 32

The same can be done with a built-in dot function.
dot(x, y)

ans = 32