Arrays

# 1. Arrays

## 1.1. Objectives

• To introduce the meaning of a data structure in computing.
• To introduce a fundamental data structure, the array.
• To show different ways arrays can be created.
• To show different ways array elements can be extracted.

## 1.2. Motivation

• One of the most common ways of organizing a collection of numbers is to place them in an array.
• The array is one of the most common data structures in computing.

## 1.3. Definitions

An array is a list of numbers. An array is an example of a data structure, which is used to organize a collection of numbers. If you know the structure, you may use a short-hand notation to refer to the entire collection or parts of a collection. For example, if an array named A contains a collection of five numbers 999,1000,1001,1002,1003, I could refer to this collection as simply A instead of saying 999,1000,1001,1002,1003. I could refer to the second and third numbers in the array by writing A([2:3]) instead of writing 1000,1001. Another example of a data structure is a matrix. MATLAB also has a cell array, which allows you to give structure to a collection of arrays and matrices.

Note that in MATLAB, arrays are called "vectors".

## 1.4. Array creation: assigning each element

In MATLAB, there are many ways to create an array. To create an array with values 1.1, 2.2, 3.3, 4.4, each element in the array can be specified individually, e.g.,

A(1) = 1.1;
A(2) = 2.2;
A(3) = 3.3;
A(4) = 4.4;
A


gives

A =

1.1000    2.2000    3.3000    4.4000


## 1.5. Array creation: short-hand method

A short-hand notation can be used instead to create an array using a comma separated list of numbers surrounded by square braces. The previous array can be created using

A = [1.1, 2.2, 3.3, 4.4];


Note that spaces after the comma are not required, and the comma is optional if the numbers are separated by spaces:

A = [1.1 2.2 3.3 4.4];


It is good practice to include the comma to remove ambiguity in certain cases. In the following, the first element is assigned the value of 2.1

A = [1.1+1 2.2 3.3 4.4]


but if there was a space before the +, the result would be a five-element array:

A = [1.1 +1 2.2 3.3 4.4]


## 1.6. Array creation: appending arrays

Arrays can be appended using the syntax

array = [array1,array2]


For example,

a1 = [1,2,3];
a2 = [4,5,6];
a = [a1,a2]


gives

 a =

1     2     3     4     5     6


## 1.7. Array creation: the colon operator

To create an array where the numbers follow a pattern such as

A = [1,2,3,4,5,6,7]


you can use the colon operator shorthand where a start, optional step, and stop value is specified

A = [start:step:stop]


e.g.,

A = [1:1:7]


If you omit the step number, it is assumed to be 1 so that the above is equivalent to A = [1:7]

If the stop value is not possible given the start and step, the last value will be the last possible value before the stop value. That is, by convention,

A = [2:2:5]


will result in an array with elements

A = [2,4]


The start, step, and stop do not need to be integers. For example,

A = [1.1:3.5:9.0]


is the same as

A = [1.1, 4.6, 8.1]


### 1.7.1. Examples

The array A = [2,4,6,8] can be created using A = [2:2:8].

The array A = [10, 8, 6, 4] can be created using A = [10:-2:4].

## 1.8. Array creation: using linspace

The function linspace can be used to create an array with values that are equally spaced. The syntax is

linspace(a,b,N)


where a is the start value, b is the end value, and N is the number of values to create between a and b (inclusive). For example

linspace(1,10,10)


gives

ans =

1     2     3     4     5     6     7     8     9    10


## 1.9. Array creation: unspecified values

 In MATLAB, you can assign a value to an element in an array even if the elements before it have not been specified. clear B; B(10) = 10.7  displays B = 0 0 0 0 0 0 0 0 0 10.7000  The first command deletes the variable B if it already exists. When you enter B(10) = 10.7, MATLAB assumes you want to create an array with 10 elements. MATLAB assigns the value of 0 to all elements below element 10 and the value of 10.7 to element 10. If you typed B(11), an error would result because B only has 10 elements. (In many programming languages, the assumed values would be arbitrary. When you create a ten-element array, 10 free slots in memory are associated with the array elements, which may already have a bit pattern. The reason that the program does not bother setting the bit patterns to zero is that it takes extra time.)

## 1.10. Accessing array elements

MATLAB uses "one-based" indexing (much like a spreadsheet, for which the first row is labeled 1). One-based indexing means that the first element is accessed with the index 1. If you entered

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A(1)


you would see

A(1) =
1.1


Because MATLAB uses one-based indexing, this statement

A(0) = 99.0


is not allowed. The only allowed values for the index are positive integers (similar to the row numbers that you see on a spreadsheet).

A(1000) = 99.0; % OK.
A(-1) = 99.0; % Error
A(1.1) = 99.0; % Error


A "zero-based" indexing program would use the index 0 to refer to the first element of an array. That is, A(0) would be 1.1.

## 1.11. Accessing multiple array elements

MATLAB allows multiple elements of an array to be accessed or displayed in various ways. To display the second and third elements, you could enter

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A([2,3]) % Best for clarity when number of elements in the access list is short as is here


or

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A([2:3]) % Best for clarity when number of elements in the access list is long


The square braces are optional:

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A(2:3)  % Allowed, and sometimes computation will be faster


Important: This will not select the second and third elements of A:

A(2,3)


because it means row 2, column 3, and the array A only has one row. If A were a matrix, then the above statement would be valid.

There is an additional notation that will be used in matrices. If instead of a single number or a list of numbers, : is used, all elements in the array are selected.

A    % Display all elements of A.
A(:) % Display all elements of A.  Same result as above.


Other examples:

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A([1:5]) % Access elements 1 through 5

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A([1,3,5]) % Access elements 1, 3, and 5

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A([2:6]) % An error because the array only has 5 elements; element 6 was never defined.

A = [1.1, 2.2, 3.3, 4.4, 5.5];
A([0,1]) % An error because A(0) is not defined (and can never be defined).

A = [1:5];
A(:) % Display all elements of A


## 1.12. The find function

The find function returns the locations in an array where a logical constraint is satisfied. For example,

A = [1,2,3,4];
I = find(A > 2)


gives

I =

3     4


The output from the find function can be used to modify elements in an array. To set all values in A that are greater than 2 to 0, one could use

A = [1,2,3,4];
I = find(A > 2); % I is the array [2,3]
A(I) = 0


## 1.13. The length function

The length function returns the number of elements in an array and is often used in Iteration.

L = length([1:10])


gives

L =

10


and

L = length([-1:1])


gives

L =

3


## 1.14. The end keyword

MATLAB has a keyword end that can be used when accessing elements of an array or matrix. end simply refers to the last element in the array or matrix and is equivalent to the value returned by the function length

A = [1:5];
A(end) % Display the last element of A.  Same as entering A(length(A))


The end keyword can also be used when referencing multiple elements of an array:

A = [1:5];
A([end-1:end]) % Display the last two elements of A.  Same as A([length(A)-1:length(A)]).


## 1.15. Row vs. column vectors and the transpose function

Thus far we have only dealt with arrays that when displayed have one row and one or more columns. For example, entering

A = [1:5]


results in the display of a one row and five column array:

A =

1     2     3     4     5


The above is referred to as a row vector in MATLAB. To create a column vector, we could use the transpose function or the transpose operator ':

transpose(A) % or A'

ans =

1
2
3
4
5


This notation and capability will become important when working with matrices and doing matrix operations. When vertically appending, the separation character is a semicolon (;) instead of a comma (,). Note that when used within square braces, the semicolon has a different meaning than if it appears at the end of a statement (output suppression).

a1 = [1,2,3]'; % Or transpose([1,2,3])
a2 = [4,5,6]'; % Or transpose([4,5,6])
a = [a1;a2]

a =

1
2
3
4
5
6


The above array a could have been created using

a = [1;2;3;4;5;6]


## 1.16. Array manipulation

MATLAB has several functions that allow arrays (and matrices) to be rotated or flipped. The transpose function and its short-hand operator ' have already been covered.

The flip function will reverse the elements in both a row and column vector.

A = [1,2,3,4,5]
flip(A) % Gives [5,4,3,2,1]
flip(A') % Gives [5;4;3;2;1]


The fliplr will only reverse elements in a row vector (a matrix with one row):

fliplr(A) % Gives [5,4,3,2,1]
fliplr(A') % Gives [1,2,3,4,5] (no change) because the ' created a column vector


The flipud function will reverse elements in a column vector (a matrix with one column):

A = [1; 2; 3; 4; 5]
flipud(A) % Results in [5; 4; 3; 2; 1]
flipud(A') % Gives [1; 2; 3; 4; 5] (no change) because the ' created a row vector


## 1.17. Array operations

The mathematical operators + and - are element-by-element operators. The sum or difference between two arrays or matrices of the same size is an array with elements that the sum or difference of the corresponding elements in the added or subtracted arrays.

Give two arrays with the same number of elements, the addition and subtraction operations result in a new array with elements that are the sum or difference of the corresponding elements of A and B:

A = [1:5]
B = [1:5]
C = A + B; % Gives [2,4,6,8,10]
C = A - B; % Gives [0,0,0,0,0]


By default, the multiplication, division, and exponentiation operations do not do element-by-element multiplication and division:

C = A*B; % Gives error
C = A/B; % Gives 1
C = A^2; % Give error


The reason is that MATLAB assumes that *, /, and ^ are matrix operations (the MAT in MATLAB is for "MATrix").

To do element-by-element multiplication, division, and exponentiation, one must precede these operator by a .:

C = A.*B; % Gives [1,4,9,16,25]
C = A./B; % Gives [1,1,1,1,1]
C = A.^2; % Gives [1,4,9,16,25]


When using the . form of the * and / operators, A and B must have the same number of elements:

A = [1:2];
B = [1:5];
C = A.*B; % Error
C = A./B; % Error


The exception is when one of the elements in the product is a scalar:

a = 2;
A = [1:3];
C = a.*A; % Gives [2,4,6] (note that a*A gives same result)
C = A./a; % Gives [0.5,1,1.5] (note that A/a gives same result)
C = a./A; % Gives [2,1,0.667] (note that a/A gives and error)


The meaning of the *, /, and ^ operators when not preceded by a . is covered in Matrices.

# 2. Problems

## 2.1. Data structure

Why are vectors used in mathematics?

## 2.2. Array creation: assigning each element

Create the array 10,11,12 by assigning each element.

## 2.3. Array creation: short-hand method

Use the short-hand method to create the same array that is created using the following commands.

A(1) = -1;
A(2) = -2;
A(3) = -3;


## 2.4. Array creation: short-hand method

What will be displayed when the following is entered on the MATLAB command line?

A = [1+2 3 4 5]
B = [1 +2 3 4 5]
C = [1+2,3,4,5]


## 2.5. Array creation: the colon operator

Write each of the following using the short-hand array creation notation.

A = [10:-2:1]
A = [10:-2:0]
A = [1,2,[7:10],3]


## 2.6. Array creation: the colon operator

Which of the following (circle them)

• A = [1:7];
• A = [1:2:7];
• A = [1:7:2];
• A = [1,2,3,4,5,6,7];
• A = [1,3,5,7];
• A = [1,3,[5:2:7]];

is the same as entering

A(1) = 1;
A(2) = 3;
A(3) = 5;
A(4) = 7;


## 2.7. Array creation: the colon operator

 Which of the following (circle each one that applies) A = [-1:3]; A = [-1:2:3]; A = [3:-1:-1]; A = [-1,0,1,2,3]; A = [-1,1,3]; A = [-1,[1,3]]; A = [-1,[1:2:3]]; is the same as entering A(1) = -1; A(2) = 1; A(3) = 3; 

## 2.8. Array creation: the colon operator

 Which of the following (circle each one that applies) A = [5:-1:2]; A = [5:1:2]; A = [5:-1:-1]; A = [5,4,3,2]; A = [5,[4:2]]; A = [5,[5:-1:2]]; is the same as entering A(1) = 5; A(2) = 4; A(3) = 3; A(4) = 2; 

## 2.9. Array creation: the colon operator

Write a program that creates the array

[9,8,7,6,5,4,3,2,1,9,8,7,6,5,4,3,2,1,9,8,7,6,5,4,3,2,1,9,8,7,6,5,4,3,2,1,9,8,7,6,5,4,3,2,1]


Using the colon operator and array appending.

## 2.10. Array creation: unspecified values

Predict what will be displayed when the following commands are executed.

clear;
A(10) = 10;
A(5) = 1;
A


## 2.11. linspace

Use linspace to create the array [-5,-4,-3,-2,-1,0,1,2,3,4,5]

## 2.12. linspace

1. Write a MATLAB expression that uses the colon operator to create a vector, a, with 50 elements that are equally spaced in the range of 0 through 2π.
2. Write a MATLAB expression that creates the same vector using the linspace function.

## 2.13. linspace and the colon operator

The following command creates an array with 101 elements:

x = [0:1:100];


Use linspace to create the same array.

## 2.14. linspace and the colon operator

The following command creates an array with 101 elements:

x = [0:1:100]/100


Use linspace to create the same array.

## 2.15. linspace and the colon operator

Use the colon operator to create the set of values x = [0,0.5,1.0,1.5,2.0,...,10.0].

Use linspace to create the same array.

## 2.16. linspace and the colon operator

Give the MATLAB expression using the colon operator that would create a vector (in a variable called vec) of 10 elements, equally spaced, from 0 through 1. Create the same vector using the linspace function.

## 2.17. linspace and the colon operator

Use the colon operator and linspace to create an array that starts at a and ends at b and has N equally spaced values by modifying only the ?? in the program below. The program should work for any values of a, b, and N.

a = 0;
b = 10;
N = 10;
A = ?? % Replace ?? with a statement using the colon operator, a, b, integers, and N.
B = linspace(??) % Replace ?? with a statement using a, b, and N.
A-B % Should be an array of zeros or values that are numerically near zero (on the order of 1e-16).


## 2.18. Accessing array elements

Describe what will happen when you enter the following on the command line (account for the semi-colon).

clear;
A(1) = 1;
A = [3,4,5,6];
A(1)

clear;
A = [2,4,5,6,7];
A(2)+A(3)

clear;
A(1) = 1.0;
A(2) = A(1) + 1.0;
A(3) = A(2) + 1.0;
A(3)


## 2.19. Accessing array elements

Describe the problem with each of the following sets of commands.

clear;
z = 10;
A(0) = z;

clear;
A(11) = 0;
A(12) = A(13);

clear;
A(-1) = 13;

clear;
1A(1) = 13;


clear;
A(1) = 12;
b = A1+1;

clear;
A = [1:13];
A(14) = A(13) + A(12)


## 2.20. Accessing array elements

Can you think of a reason why a program would use zero-based indexing?

## 2.21. Accessing array elements

When the following program is entered,

A = [1:100];
b = A(1)
b = A(0)


the result is


b =
1

??? Attempted to access A(0); index must be a positive integer or logical.


Why did this error message occur?

## 2.22. Accessing array elements using the colon operator

Create a 100-element array with consecutive integers starting at zero. Use the colon operator to display the 5th and 6th elements.

## 2.23. Accessing array elements using the colon operator

Create a 100-element array with consecutive integers starting at zero. Use the colon operator to display every third element starting at the location in the array that has the value 3.

## 2.24. The end keyword

Using the end operator, write a command that creates an array with 100 elements and then displays the last three elements using the end keyword.

## 2.25. The end keyword

Using the end operator, write a command that creates an array with 100 elements and then displays the numbers 100, 97, 94, ..., 1.

## 2.26. length and end

Write a command that displays the last four element of A using (a) the length function and (b) the end keyword.

## 2.27. length

Use the length function as a part of a statement that is equivalent to

A(:)


## 2.28. The transpose function

What must be ? be replaced with below to produce the given output?

A = [1:5]
A = ?

ans =

1
2
3
4
5


What will be displayed when the following is entered?

A = transpose([1:5]')
A = transpose([1:5])'


## 2.29. Row vs. column vectors and appending arrays

Write a single command in place of ?? below that will create the displayed array. What you write may only contain the symbols [, ], ', , and ;.

A = [1:3];
??
A =

1     2     3     1     2     3


## 2.30. Row vs. column vectors and appending arrays

Write a single command in place of ?? below that will create the displayed array. What you write may only contain the symbols A, [, ], ', , and ;.

A = [1:3];
??
A =

1
2
3
1
2
3


## 2.31. Row vs. column vectors and appending arrays

Write a single command in place of ?? below that will create the displayed array. What you write may only contain the symbols A, [, ], ', , and ;.

A = [1:3];
??
ans =

1
2
3
1
2
3


## 2.32. Row vs. column vectors and appending arrays

Write a single command in place of ?? below that will create the displayed array. What you write may only contain the symbols A, [, ], ', , and ;.

A = [1:3];
??
ans =

1     1
2     2
3     3
1     1
2     2
3     3


## 2.33. Array manipulation

What will be displayed when the following commands are entered?

A = [1:5]
B = flip(A)

A = [5:-1:1]
B = fliplr(A)

A = [1:5]
B = fliplr(flip(A))

A = [1:5]
B = flipud(A')

A = [1:5]
B = fliplr(A')


## 2.34. Writing a function that creates an array I

Write a function that takes an input of an array and returns the same array except with the last element removed.

## 2.35. Writing a function that creates an array II

Write a function that takes an input of an array and returns the same array repeated. For example, if the input is [1,2,3], the output should be [1,2,3,1,2,3].

## 2.36. Array operations

Predict what will be displayed when the following commands are executed.

 clear
A = [1:10];
A([1:5]) + A([5:-1:1])


## 2.37. Array Operations

The plot function takes two inputs corresponding to x and y values to plot; entering plot(x,y) on the command line will open a plot window if x and y have been defined.

1. Write a program that will plot y = x2 from x = 0-10 in increments of 0.5.
2. Write a program that will plot y = sin(x) from x = 0 − 4π in increments of π / 10.
3. Write a program that will plot y = sin(x) from x = 0 − 4π in increments of π.

# 3. Video Tutorial

## 3.1. Video

(Note - the video is available in HD - go to full-screen mode if fonts are too small)

### 3.1.1.

Create an array with elements 100, 102, 104, 106, and 108 using three different techniques. When you enter the name of the array on the command line, you should see:

A =

100 102 104 106 108


### 3.1.2.

When would you not want to use the 3rd technique covered in the video for creating an array?

### 3.1.3.

What does the following command do?

B = [-100:-10:-200]


### 3.1.4.

What do you expect to happen when you type the following? Do you agree that the command should not be classified as an error by MATLAB?

C = [1:10:2]


### 3.1.5.

Do arrays always need to be named with upper-case letters?

### 3.1.6.

Describe the array that will be created when the following commands are entered:

clear;
D(10) = -10
D(9)  = -9
D(11)

clear;
E = [1:1:10];
E(11) = 13
E(20) = 20