Matrix (and array/vector) operations We will treat a vector (mathematical name for array) of some length N as a matrix of size Nx1 (or 1xN if necessary). So any Matrix operations we describe below apply to vectors too. A = (2x3) 1 2 3 4 5 6

B = (3x2) 1 2 3 4 5 6

u = (row vector 1x3) 1 2 3

v = (column vector 3x1) 1 2 3

Statements to create these in MATLAB: A = [1 2 3; 4 5 6]; B = [1 2; 3 4; 5 6]; u = [1 2 3]; v = [1; 2; 3]

C = (2x3) 1 0 1 1 0 1

C = [1 0 1; 1 0 1];

Addition and Subtraction of a matrix with a scalar Adding a scalar to a matrix adds it to each element of the matrix. Example: D = A+1; produces D = [2 3 4; 5 6 7];

Addition and Subtraction of two matrices Matrices A and B can be added together only if they are of the same dimensions. D = A + B; - Does not work! D = A + C; produces D = [2 2 4; 5 5 7];

Multiplication of two matrices Matrices can be multiplied only if the number of columns in the first matrix are equal to the number of rows in the second matrix. D = A * B; produces D = [22 28; 49; 64]; D = A * C; - Does not work! D = A * v; produces D = [14; 32] w = u * v; produces w = 14

Element by element multiplication Sometimes, we need to do element wise multiplication, for example to apply a mask. Placing a dot before the operator makes it act this way. D = A .* C; produces D = [1 0 3; 4 0 6]; Remember that the regular A * C doesn't even work.

Transpose The apostrophe symbol transposes a matrix or a vector. D = A'; produces D = [1 4; 2 5; 3 6]; w = v'; produces w = [1 2 3];

Concatenation We can glue together matrices if their dimensions match, by writing them inside [ ] separated by a space. D = [A C]; produces D =[ 1 2 3 1 0 1; 4 5 6 1 0 1];

Matrix inversion Most of the time, we only invert square matrices. D = A * C; produces D = [22 28; 49 64]; - a square matrix. E = inv(D); produces E = [ 1.7778 -0.7778; -1.3611 0.6111 ]; ['My student ID is: ' num2str(ID)] is a concatenation of two character vector.

Solving linear equations 8x+1y+6z=1 3x+5y+7z=2 4x+9y+2z=3 The solution to a set of linear equations is formulated as: If A * x = b, where A = [ 8 1 6; 3 5 7; 4 9 2] and b = [1; 2; 3], then x = inv(A) * b; If the number of equations is more than the number of unknowns, the best least-squares solution is obtained by using the \ operator. It is recommended to use the \ operator over inv() at all times, even when A is square. x = A \ b;

Zeros, Ones and Magic squares A = zeros(N) creates a matrix filled with zeros, with N rows and N columns. A = zeros(M,N) creates a zero matrix with M rows and N columns. ones(N) or ones(M,N) create a matrix filled with ones. A = magic(N) creates a square matrix where the sum of all rows and columns is a contant.

Exercise 1. Solve the following system of equations using MATLAB: 4x + y – 2z = 0 2x – 3y + 3z = 9 -6x -2y + z = 0

2. Given vectors u = [1; 2; 3; 4] and v = [5; 6; 7; 8]. Find their dot product and cross product. 3. Concatenate the matrix A = [1 2 3; 4 5 6] with itself to produce the following matrix: 1

2

3

1

2

3

4

5

6

4

5

6

1

2

3

1

2

3

4

5

6

4

5

6

1

2

3

1

2

3

4

5

6

4

5

6

4 Print the squares of the first 100 natural numbers.

Control Statements The statements we have encountered so far either assign values to variables, do computations on them, and print their results. Control statements let you change the execution order of the program based on the contents of variables. Here is a short example using the 'if' statement: my_cash = 80; my_piggy_bank = 20.27; game_cost = 45; my_money = my_cash + my_piggy_bank; if (my_money > game_cost) disp('I am buying a videogame!'); my_money = my_money - game_cost; disp(['I am left with $' num2str(my_money)]); else disp('I am broke!'); end You can figure if your cash was only $20, the program will display 'I am broke!', instead of making a video game purchase. A more complex type of if statement checks for many conditions: if (condition 1) do stuff elseif (condition 2) do stuff elseif (condition 3 etc.) do stuff end

Exercise Write a script that checks the value of a variable called score, and prints the message Your grade is X where X is A if score >= 90, B if score >=80, C if score >=70, D if score >=60, otherwise F.

Math functions Expression

Description

y = sin(x) y = cos(x) y = tan(x)

Trigonometric functions. x is in radians.

x = asin(y) x = acos(y) x = atan(y)

Inverse-trigonometric functions. x is in radians.

sind, cosd, tand, asind, acosd, atand The same functions but work in degrees instead of radians. y = x^2; or y = x^10

Raise x to the nth power.

y = sqrt(x)

Square root.

y = exp(x)

ex.

y = ln(x), y = log(x)

Natural and base 10 log functions.

x = [1 2 3 4], y = sum(x);

Sum of the elements of an array.

x = [1 2 3 4], y = mean(x);

Mean of the elements of an array.

x = [1 2 3 4], y = std(x);

Standard deviation of the elements of an array.

These functions work on both scalars and vectors/matrices. Instead of computing y for a single value of x, we can compute it for a whole bunch of values in a single statement. Plotting sin(x) for x = -pi to +pi The linspace function can be used to generate desired number of points between a start and and end value. Usage: Points = linspace(start value, end value, number of points). x = linspace(-pi, +pi, 100); y = sin(x); plot(x, y); title('Plot of sin(x)'); Choosing more number of points produces a smoother looking plot.

Exercise Write a script that plots the following functions for the given range of x: a) sin(x) for x from 0 to 2*pi b) cos(x) for x from 0 to 2*pi c) tan(x) for x from 0 to pi d) e-5x for x from -2 to 2 e) Generates a vector of 10 random numbers u. Print their sum, mean and standard deviation.

Complex Numbers Can be stored in variables just like other numbers we've been storing. One complex number needs just one variable. Example of a complex number: x = 5 + 3*i The variables i and j represent sqrt(-1).

Extracting the real and imaginary parts x_real = real(x); x_imag = imag(x);

Converting from Cartesian to polar [theta rho] = cart2pol(x_real, x_imag);

Converting from polar to Cartesian [x_real, x_imag] = pol2cart(theta, rho);

Finding the magnitude and angle theta = angle(x); magnitude = abs(x);

Plotting complex numbers If the real axis is along the x axis and the imaginary axis is along the y axis, we can plot a complex number simply as: plot(x_real, x_imag, 'o'); The third argument improves visibility by drawing a small circle at the complex number's location. It also prevents MATLAB from connecting complex numbers with lines.

Exercise a) Write a script to plot the Nth roots of -1. The roots are complex numbers given by the following equation: root = ej(pi/N + 2*pi*k/N) for k = 0 to N-1 b) Convert the following to polar coordinates: 2+3j and -5-2j c) Convert the following to Cartesian coordinates: Rho = 5, angle = 45o