Introduction to Simulation: Beginner


Built-in Functions


There are many built-in functions in MATLAB, we will go through some of them.

sin(0)
cos(0)
tan(0)

ans = 0
ans = 1
ans = 0

Interesting thing is that because MATLAB works basically with the matrices, we can pass matrices as the function arguments.
A
sin(A)

ans =
   0.8415   0.9093
   0.1411  -0.7568

What it does is calculates the sine of every element of A and returns a matrix the same size as A. If we check it separately, we'll get the same result.
sin(1)
sin(2)
sin(3)
sin(4)

ans = 0.8415
ans = 0.9093
ans = 0.1411
ans = -0.7568

So all MATLAB functions work generally like that.
Some other functions you might want to use is the exponential function.
exp(1)
exp(2)

ans = 2.7183
ans = 7.3891

There is the log, which is the opposite of the exponential:
log(1)
log(2)
log(exp(1))

ans = 0
ans = 0.6931
ans = 1

We can get square root as:
sqrt(25)
sqrt(11)

ans = 5
ans = 3.3166

So, these are some elementary functions in MATLAB.


There are also some built-in constants, for example, pi.

pi

ans = 3.1416

If you do something like creating a variable called pi and you assign it to something else.
pi = 2


pi = 2

Then we cannot use the original variable pi anymore.
pi

pi = 2

So it is better to avoid overriding the built-in constants. If we want pi back, we need to go to the workspace and delete pi. So, if we type pi again it's now back to the original pi.
clear
pi

ans = 3.1416


For some reason, MATLAB does not have a variable e, so if you want it, you can create it manually and assign it to exp(1).

e = exp(1)

e = 2.7183

Another important constant is i. If we do sqrt(-1), we get 0 plus 1 times i.
sqrt(-1)

ans =  0 + 1i

We can just type i and it would give the same answer:
i

ans =  0 + 1i

We can do exponents using the hat symbol, so we can do i^2, that also gives -1.
i^2

ans = -1


There are also some important functions for initializing matrices. The first one is the I function where I is the identity matrix. It is a square matrix with ones on the diagonal and zeros everywhere else. Suppose we want to create 3-by-3 identity matrix. We can do that manually.

I = [1 0 0; 0 1 0; 0 0 1]

I =
   1   0   0
   0   1   0
   0   0   1

It is quite inefficient. Instead, we can do eye(3) which is much more convenient.
eye(3)

ans =
Diagonal Matrix
   1   0   0
   0   1   0
   0   0   1

Another thing we might want to do is to create a matrix of all zeros. That's the function zeros().
zeros(4)

ans =
   0   0   0   0
   0   0   0   0
   0   0   0   0
   0   0   0   0

If we don't want the matrix to be square, we simply need to define the second dimension.
zeros(3,2)

ans =
   0   0
   0   0
   0   0

There is also a function called ones which does a similar thing, it creates a matrix of all ones.
ones(3,2)

ans =
   1   1
   1   1
   1   1