Basic Math

Math in MATLAB closely follows the rules of linear algebra:

  • anything that can be done in linear algebra can be done in MATLAB,
  • most thing that aren’t allowed in linear algebra aren’t allowed in MATLAB.

Operators

MATLAB has standard operators,

Nothing to say when x and y are scalars, different situation when are matrices.

Matrix addiction/subtraction

Matrix multiplication

It requires the inside dimensions to be the same or one input to be a scalar.

Matrix Division

Matrix division is not generally defined in linear algebra, we can think about it as a set of linear equations.
Suppose we have z an M by L

yz = x

where x is N by M and y is N by L. The result of the division is the solution of the linear system, that is obtained by OLS,

z = (y’y)^-1y’x

>> z = x/y

As linear regression, matrix division is only well defined if y is nonsingular therefore full rank.
Note:This is the matrix right division (/), there is also matrix left division (\). They are related by the equation B/A = (A’\B’)’.

. operator (dot operator)

The . operator turns usual operations into element by element operations. For instance, suppose x and y are N by N matrices.

z = x .* y

produces z where

z(i,j) = x(i,j) * y(i,j)

.
The same applies to division (./) and exponentation (.^). It cannot be used when the matrices have different dimensions.

Transpose

In order to transpose a vector or a matrix use .
For example, A is a M by N and A’ is a N by M

>> A'

Parentheses and Precedence

Parentheses are used as usual in the math expressions, they can be nested to create more complex ones.
Remember you can use only round brackets to control the order of the math expressions.

Important remark

Unary operators are + or – operations that apply to a single element, consider (-4) this is an example of unary since there is only 1 operation.
If we type on matlab -4^2 we get -16 since MATLAB interprets this as -(4^2) since – is no longer unary. We have to type (-4)^2.

Exercises

  • Download from here the mat-file and load it.
  • Compute A’*B’*C. What do you have to change in order to make a valid MATLAB statement by using a dot product in this expression?
  • Compute (C + D)^2, is it possible? drop out last column of both matrices.
  • Is it the same of C^2+C*D+D*C+D^2? and C^2+2*C*D+D^2?
  • Compute Z = b’/B’ compare it with the solution of the linear system obtained by OLS (hint: the MATLAB command to obtain the inverse is inv() ). Is it the same? Compute also the left division.
%d bloggers like this: