Arrays
From ComputingForScientists
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 shorthand 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: shorthand method
A shorthand 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 fiveelement 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 If you typed (In many programming languages, the assumed values would be arbitrary. When you create a tenelement 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 "onebased" indexing (much like a spreadsheet, for which the first row is labeled 1
). Onebased 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 onebased 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 "zerobased" 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([end1: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 shorthand 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 elementbyelement 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 elementbyelement 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 elementbyelement 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?
Answer 

It allows for simplified notation. 
2.2. Array creation: assigning each element
Create the array 10,11,12
by assigning each element.
Answer 

A(1) = 10; A(2) = 11; A(3) = 12; 
2.3. Array creation: shorthand method
Use the shorthand 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: shorthand 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 shorthand array creation notation.
A = [10:2:1] A = [10:2:0] A = [1,2,[7:10],3]
Answer 

A = [10:2:1] is the same as A = [10, 8, 6, 4, 2] Note that A = [10:2:0] is the same as A = [10, 8, 6, 4, 2, 0] A = [1,2,[7:10],3] is the same as A = [1,2,7,8,9,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;
Answer 


2.7. Array creation: the colon operator
Which of the following (circle each one that applies)

is the same as entering A(1) = 1; A(2) = 1; A(3) = 3; 
Answer 


2.8. Array creation: the colon operator
Which of the following (circle each one that applies)

is the same as entering A(1) = 5; A(2) = 4; A(3) = 3; A(4) = 2; 
Answer 

The following commands produce the correct array:

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
Answer 

The array 
2.11. linspace
Use linspace
to create the array [5,4,3,2,1,0,1,2,3,4,5]
Answer 

The following creates a list of 11 numbers with the first and last elements being 5 and 5, repectively. linspace(5,5,11) 
2.12. linspace
 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π.  Write a MATLAB expression that creates the same vector using the
linspace
function.
Answer 

A = [0:(2*pi)/49:2*pi] B = linspace(0,2*pi,50) A common error is to write A = [0:(2*pi)/50:2*pi] but this creates an array with 51 values: [0, 2*pi*(1)/50, 2*pi*(2)/50, 2*pi*(3)/50, ..., 2*pi*(50)/50] 
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.
Answer 

x = linspace(0,100,101); 
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.
Answer 

x = linspace(0,1,101) 
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.
Answer 

x = [0:0.5:10] x = linspace(0,10,21) 
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.
Answer 

linspace(0,1,10) % Note that the width of the interval is not equal to 1/10. % It is 1/9. 
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. AB % Should be an array of zeros or values that are numerically near zero (on the order of 1e16).
2.18. Accessing array elements
Describe what will happen when you enter the following on the command line (account for the semicolon).
clear; A(1) = 1; A = [3,4,5,6]; A(1)
Answer 

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

The value 
clear; A(1) = 1.0; A(2) = A(1) + 1.0; A(3) = A(2) + 1.0; A(3)
Answer 

The third line results in 
2.19. Accessing array elements
Describe the problem with each of the following sets of commands.
clear; z = 10; A(0) = z;
Answer 

The first element of an array is 
clear; A(11) = 0; A(12) = A(13);
Answer 

The command 
clear; A(1) = 13;
Answer 

The first element of an array is labeled with 
clear; 1A(1) = 13;
Answer 

Variable names may not start with a number. 
clear; A(1) = 12; b = A1+1;
Answer 


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

The command 
2.20. Accessing array elements
Can you think of a reason why a program would use zerobased indexing?
Answer 

In binary, integers are stored like this:
etc. Zerobased indexing just allows counting to start at zero, which is more natural because there is a onetoone correspondence between decimal zero and binary zero. 
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?
Answer 

The error message occurred because MATLAB does not use a zerobased indexing system; it uses onebased indexing meaning the first value of an array would be A(1). 
2.22. Accessing array elements using the colon operator
Create a 100element array with consecutive integers starting at zero. Use the colon operator to display the 5th and 6th elements.
Answer 

A = [0:99]; A([5:6]) 
2.23. Accessing array elements using the colon operator
Create a 100element 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.
Answer 

A = [0:99]; A([4:3:end]) 
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.
Answer 

A = [1:100]; A([100:3: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.
 Write a program that will plot y = x^{2} from x = 010 in increments of 0.5.
 Write a program that will plot y = sin(x) from x = 0 − 4π in increments of π / 10.
 Write a program that will plot y = sin(x) from x = 0 − 4π in increments of π.
Note: For information on plotting, see also [1].
Answer 

x = [0:0.5:10]; y = x.^2; figure(1); % Opens figure window named "1" clf; % Clears any existing plot in this figure. plot(x,y); x = [0:pi/10:4*pi]; y = sin(x); figure(2);clf; plot(x,y); x = [0:pi:4*pi]; y = sin(x); figure(3);clf; plot(x,y); % Note that the values are not all zero in last plot as may % have been expected. This is due to finite precision of pi. % Difference from zero is on the order of 1e16. See help eps. % To get all zeros, use % x = [0:180:4*180]; % y = sind(x); % See help for sind which notes that for integer n, % sind(n*180) is exactly zero, whereas sin(n*pi) reflects % accuracy of floating point value of pi. 
3. Video Tutorial
3.1. Video
(Note  the video is available in HD  go to fullscreen 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
Answer 


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

If you want to create an array with many numbers, you would not want to manually enter each element. For example, if you want to create an array with the numbers 
3.1.3.
What does the following command do?
B = [100:10:200]
Answer 

The command creates an array, 
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]
Answer 

This command will create an error. This command is saying, "Start with 1 and add 10 until you reach 2." We know that this is impossible. 
3.1.5.
Do arrays always need to be named with uppercase letters?
Answer 

Arrays do not have to be named with uppercase letters. However, uppercase letters are usually used to signify an array or matrix. 
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)
Answer 


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

