# Intro to MATLAB Unit 2: MATLAB ARRAYS (VECTORS, MATRICES, AND STRINGS)

## Contents

- Arrays
- One-dimensional arrays (Vectors)
- Two dimensional arrays (Matrices)
- Array indexing
- Transposition
- Built-in MATLAB functions for arrays/matrices
- Addition and subtraction
- Multiplication
- Division
- Element-wise operations
- Example: Solving systems of equations using matrices
- Strings
- Multiple dimension arrays
- Practice problems!

## Arrays

MATLAB loves arrays (MATLAB stands for MATrix LABoratory). Arrays can represent vectors or matrices and can be stored in variables. Arrays are MATLAB's standard way of representation. That is, even a scalar numerical value (as a = 1) and strings are represented by arrays.

## One-dimensional arrays (Vectors)

A one-dimensional array is a list of scalar values arranged in a row or column.

%Row vector: value separated by commas rowVector = [27, 972, -198273, 0, 712] %Column vector: values separated by semi-colons columnVector = [27; 972; -198273; 0; 712]

Vectors can also be created with evenly spaced values using **colon notation** or **linspace**.

% In colon notation, the first number represents the starting value, % the middle number represents the spacing, and the last number % represents the ending value: newVector = 2:2:10 %Linspace is useful if you don't know what the spacing should be: newVector = linspace(2,9,7)

Try this yourself:

- What if the ending value doesn't match up with the spacing?
- Can you have a negative spacing?
- Can you have a decimal spacing?

%Variables and numbers can be combined to make vectors: x = 7; y = 23; newVector = [19, x, 37, y, x / y] %You can even combine two vectors into a larger vector: vectorA = [2:2:12] vectorB = [-9:-3:-15] vectorAB = [vectorA vectorB] vectorBA = [vectorB vectorA]

## Two dimensional arrays (Matrices)

Use both rows and columns.

% Separate columnss by comma and rows by semi-colon: newMatrix = [4, 2, 9; 1, 0, 3; 1, 9, 9] %Can also be done using multiple lines: newMatrix = [4 2 9 1 0 3 1 9 9] %You can use variables and expressions to create matrices / vectors: x = -2 * pi : pi / 2 : 2 * pi trigMatrix=[sin(x) cos(x)] %You can use a combination of colon notation, linspace, and vector variables: newMatrix = [2:4:22; linspace(-3, 9, 6); vectorA] %When creating a Matrix, you must ensure that each row has the same number of columns: newMatrix = [1 2 3 4 5] % <- this will lead to an ERROR

## Array indexing

For vectors, typing a number in parenthesis afer the variable name will retrieve the value at that address/index. The same can be done with matrices, but it requires two values. The first value selects the row and the second selects the column.

NOTE: it is a useful convention to use uppercase variable names for matrices and lowercase variable names for vectors.

v = [18 -20 25 4 -1] A = [18 -20 2; 9 11 -14; 1 -1 100; 4 12 5] v(3) A(3,2) % Use this to change individual values within a matrix or vector: v(5) = 100 A(1, 2) = 100 %Colon notation can be used to select more than one value within a % vector or matrix: v(2:4) A(1:2, 2:3) %A colon by itself selects all of the rows or columns: A(:, 2:3) A(1:3, :) %As before, you can replace sections of a matrix or vector using this %notation: v(2:4) = [-11 999 0] A(:, 1:2) = [55 66; 88 99; 10000 -10000; 9 99] %Vectors and Matrices can be increased in size using this method as well: v(10) = 100000 A(7, 8) = -999 %Note that if the values aren't specified they are automatically %filled in with zeroes. Sometimes it's better to go ahead and specify %a whole new row or column: B = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] B(5,:) = [17:20] B(:,5) = [1:5] %You can delete sections of vectors and matrices by using [] (empty vector): v(1:3) = [] % erases first three entires B(:,3) = [] % erases third column %When deleting items from a matrix, you must delete and entire row or %column. (why?) B(2,3) = [] % <- this will lead to an ERROR %Let's say I wanted to double the size of newMatrix, keeping the same values %but having each of them included twice. B(6,5) = B % <- this will lead to an ERROR B(5:8,5:8) = B % you must specify the size of the matrix that you're appending %To 'flatten' your matrix to a vector use (:) a = A(:)

## Transposition

Using an ' after a variable name will transpose it. Transposition makes the rows into the columns and the columns into the rows. It can be used with vectors or matrices.

```
v = [18 -20 25 4 -1]
A = [18 -20 2; 9 11 -14; 1 -1 100; 4 12 5]
v_transposed = v'
A_transposed = A'
% compare the sizes
length(v), size(v)
length(v_transposed), size(v_transposed)
```

## Built-in MATLAB functions for arrays/matrices

length(v) % length (of a vector) size(A) % size (of a matrix) max(v) % max entry in v max(A(:)) % max entry in A max(A) % max entry in each column (same: max(A,[],1)) max(A,[],2) % max entry in each row (same: max(A')) [m,idx] = max(A) % max entry in each column (m) and their indices (idx) mean(v) % mean of all entries in v mean(A(:)) % mean of all entries in A

Other useful functions are min(), median(), std(), and var(). Use the help to find out more about these functions.

```
%The built-in Matlab functions for scalars generally apply to each array element:
x = [-3 * pi : pi / 8 : 3 * pi]
y = cos(x)
```

Often we need the identity matrix and an inverse of a given matrix. There are two ways to get the inverse in MATLAB. The all zeros and all ones matrices can be useful for initialization.

zeros(3), zeros(3,4) % all zero matrix ones(2), ones(3,2) % all ones matrix I = eye(3) % identity matrix % multiplying a matrix by the identity matrix doesn't change it A * I

CAUTION: only **square matrices** with a non-zero determinant have an inverse.

A = [18 -20 2; 9 11 -14; 1 -1 100] det(A) % determinant of a matrix Ainv = A^(-1) % inverse of a matrix Ainv = inv(A) % inverse of a matrix

Other useful functions for matrices are diag(), triu(), trace(), rank(), cond(), norm(), eig(), eigs(), svd(), chol(), and expm(). Use the help to find out more about these functions.

NOTE: the computations of most of these functions are simple but large, and not in the scope of this class.

## Addition and subtraction

Simple, exactly like adding or subtracting scalars. Arrays must be the same size to perform addition or subtraction.

A = [4 -10 11 -23; 9 14 -12 7] B = [-2 1 15 -11; 10 7 4 2] C = A + B C = A - B %Adding or subtracting a scalar will apply the operation to each element in %the array A + 12 B - 9

## Multiplication

For starters: Multiplication can only be carried out on Matrices if the left Matrix has the same number of columns as the right matrix has rows. You will recieve an error otherwise!

A * B % <- this will lead to an ERROR B = B' % transpose B C = A * B %Multiplication is the sum of products of rows and vectors from each %matrix. For example: C(1,1) A(1,1) * B(1,1) + A(1,2) * B(2,1) + A(1,3) * B(3,1) + A(1,4) * B(4,1) %Or: A(1,:) * B(:,1)

The above is an example of vector multiplication. When multiplying vectors, there must be one row vector and one column vector. This is called the dot product of two vectors.

Matlab includes a "dot" command which will compute the dot product of two vectors with the same length, even if they are both rows or columns.

a = [24 123 -19] b = [-1 14 -68] dot(a, b) % inner product (scalar product, dot product) a * b' % inner product (scalar product, dot product) a' * b % outer product (tensor product, dyadic product) a * b % <- this will lead to an ERROR %Array multiplication is NOT commutative A * B B * A %Even if the multiplication can be carried out in each direction (i.e. %the arrays are square) the result will be different squareA = [18 -20 2; 9 11 -14; 1 -1 100] squareB = [-12 73 22; -10 -11 0; 85 2 90] squareA * squareB squareB * squareA % a matrix times its inverse equals the identity squareA * inv(squareA) inv(squareA) * squareA

## Division

When I think of matrix division I'm always reminded of fraction division: To divide fractions you first find the inverse and then multiply. The same is true for matrices, but since matrix multiplication and division aren't commutative, there are two different ways to divide. Left division inverts the left matrix and multiplies (cf. ). Right division inverts the right matrix and multiplies (cf. ).

% Left division squareA \ squareB inv(squareA) * squareB % Right division squareB / squareA squareB * inv(squareA) %Notice that because we are inverting, division can only be %accomplished with square matrices %If you wish to divide by a scalar, use right division: A / 2 B \ 4 % <- this will lead to an ERROR

## Element-wise operations

If you wish to perform operations between the specific elements of two matrices or vectors, you should use element by element operations. This is achieved by putting a "." in front of the operation you wish to use. IMPORTANT: the "." is needed because *, /, and ^ refer to linear algebra operations within MATLAB. We will visit these operations in more detail in the future.

IMPORTANT: The matrices need to be the same size.

A = [4 -10 11 -23; 9 14 -12 7] B = [-2 1 15 -11; 10 7 4 2] A .* B % element-wise multiplication A ./ B % element-wise division A .^ B % element-wise power A .* [2, 3; 4, 5] % <- this will lead to an ERROR % + and - are already element by element: A + B A - B %Operations involving scalars are typically element-by-element by default: 5*A B-10 %Element by element operations are useful for computing the result %of a function for many different inputs: x = [-3:3] y = (x.^2 + 10.*x) ./ (-2.*x.^3 - 5)

## Example: Solving systems of equations using matrices

Often times, we will have a system of two or more equations that we would like to solve. If there are at least as many equations as there are variables, matrix multiplication or division is a simple and effective way at solving these systems.

%Let's examine the following system of equations: % 3x - 4y + 10z = -2 % x + 11y - 9z = 7 % -2x + 5y + z = 3

We can break up the above system into three parts: since we're solving for the variables it would be nice to separate them from the rest of the system. This leaves us with the coefficients and the answers. If we look at the coefficients we can see that they clearly form a 3 by 3 square matrix:

A = [3 -4 10 1 11 -9 -2 5 1]

Following the same idea, the values to the right of the equals sign appear to form a vector (specifically a column vector):

b = [-2; 7; 3]

Now, back to the variables. How do they fit in this picture? Well, if we want to get our original equations back, we'd need to multiply the coefficient matrix by a vector containing our variables. We won't actually make this vector (we're about to solve for it).

%Our problem looks something like this: % 3 -4 10 x -2 % 1 11 -9 * y = 7 %-2 5 1 z 3

We can write the above in a formula with the form A * X = B, where A is the coefficient matrix, B is the answer vector, and X is the vector of unknowns being solved for. We have already discussed how a matrix multiplied by its inverse is the identity matrix, so to solve our formula for x we could do:

```
X = inv(A) * b
%Which is the very definition of left division:
X2 = A \ b
```

We will end up with a column vector containing the values of our variables.

%To verify: 3*X2(1) - 4*X2(2) + 10*X2(3) %Should be -2, as per the first equation

## Strings

A string can be thought of as an array of characters. To create a string, surround the characters you would like with single quotes. The characters use what is called ascii format. The letters in the sentence are represented by numbers.

newString = 'My name is Anna' %Why wouldn't this work? (What does MATLAB think is happening?) newString = My name is Anna % <- this leads to an ERROR

NOTE: the whos command will tell us what is in these vectors. They have a different type (char) than the vectors and matrices we have been using before.

whos % Use the whos command OFTEN!!! %The addressing/indexing rules for arrays also apply to strings: newString(5) newString(12:15) newString(12:15) = 'Duck' % replacement %What if I want to replace my name with a name of a different length? newString(12:15) = 'Charles' % <- this will lead to an ERROR % (why?) newString = [newString(1:11) 'Bob'] % Correct way (create a new vector % using pieces of the old one): length(newString) % vector functions also work with strings

Strings can also be put into Matrices. The best way to do this is with the "char" command:

newString = char('Name:', 'TROGDOR the BURNINATOR', 'Species:', 'Dragon-Man')

NOTE: the char command pads the strings so that they all are the same length (a requirement for matrices) It achieves this by adding spaces to the ends of the strings until they are all the same length You could do this yourself manually, but take advantage of the char function!

CAUTION: Do not mix up strings with scalars or other data types: They may look the same, but because their type is different they will behave differently:

x = '1' y = 1 x + y % this adds the ascii representation of '1' (which is 49) to 1 y + y % y is a scalar, so the addition works as we'd expect. whos % Use the whos command OFTEN!!!

## Multiple dimension arrays

So far we have seen 1D arrays (vectors) and 2D arrays (matrices), but in reality you can create an array with as many dimensions as you'd like. For a 3D array, this additional dimension is represented with additional pages.

% For example say we have the following 2D arrays: x = [1:3;4:6] y = 10 * x; z = 10 * y; w = 10 * z; %We could create a 3D array as follows: threeD(:,:,1) = x; threeD(:,:,2) = y; threeD(:,:,3) = z; threeD(:,:,4) = w; %We now have an additional index to worry about. threeD(1, 2, 3) threeD(2, :, 2) threeD(1, :, :) threeD(:, :, 2)

## Practice problems!

**ARRAY CREATION 1**

What will be the result of the following lines of code?

x = [-5:-3:-17] y = [10:15:5]' z = [2:2:8; 4:4:16; 15:-4:3]

**ARRAY CREATION 2**

Write a line of code that will create a row vector with values between 17 and 117 with a spacing of 10.

Write a line of code that will create 7 evenly spaced values between 17 and 117.

**MATRIX ALGEBRA 1**

Write the result of the following equations:

m = [4 -9 7 3]; n = [11 5 -2 17]; o = [1 0 8 0]; p = m * n'; q = o' * m;

What is p? What is q?

**MATRIX ALGEBRA 2**

```
A = [2 7; -4 0]
B = [9 2 3; -5 0 -6]
C = [-1 8; 3 -4; 5 5]
D = A * B;
E = A * C; % <- this will lead to an ERROR
```

What is D? What is E?

**MATRIX ALGEBRA 3**

Write code that will solve the following system of equations using matrix operations:

%3x + 2y + 5z = 22 %4x + 5y -2z = 8 %x + y + z = 6

The ^ operation works the same with matrices as it does with scalars: A^3 will try to multiply A by itself like so: A * A * A. What must be true about A for this to work?

```
%Solution to final problem:
E = [3 2 5; 4 5 -2; 1 1 1];
s = [22; 8; 6];
v = E \ s
```

**ELEMENT-WISE OPERATIONS 1**

You are given the following:

C = [10, 11, 12; 5, 4, 2] D = [-1, 4, -2; 7, -11, 9] E = [4, 4, 5, 11, 2]

**ELEMENT-WISE OPERATIONS 2**

What is the result of the following?

x = C .* D - 5 y = D.^2 z = E.^2 - 3.*E + 1 v = [D(1,2), D(2,3), E(4)] w = [C(2,1), D(2,:)]

Lecture notes for CSE200 (Fall 2015) at Washington University in St. Louis by Marion Neumann (based on materials from Doug Shook).