Numeric arrays

Overview

This module is about Numeric Arrays, which are arrays that contain numbers (as opposed to characters or booleans).

Module Organization

This module is broken down into the following sections:

  1. Numeric Arrays
  2. Using MATLAB as a Calculator

Learning Objectives

After completing this module, you should be able to:

  • Assign a numeric value to a variable using proper syntax and naming conventions
  • List which special characters are used to:
    • concatenate numbers
    • create a new row in a matrix
    • transpose a matrix
    • create a range of numbers or indices
    • index a variable
  • Delete any elements from an array using an empty pair of square brackets.
    • Discuss the consequences of deleting elements on the shape of the resultant array
  • Use both standard and linear indexing on numeric arrays to extract values from elements
  • Use MATLAB as a calculator.

Module Conventions

Throughout these modules, the following conventions are used:

  • MATLAB functions and variables are bold or italicized, respectively.
  • Code blocks containing MATLAB code are lightly shaded, as such:
matlab code

  • Double greater than signs (>>) in the code block indicate that you should type that line in the Command Window

Special Characters

Character Name Function
[ ] square bracket concatenate
( ) parentheses index, pass variables
; semi-colon new line, end of line
: colon indicates range
' single quotations transpose

Relevant Mathworks Tutorials


Numeric Arrays

Top | Numeric Arrays | Using MATLAB as a Calculator

When you want to store a number in a variable, you need to create a numeric array. This is very easy to do in MATLAB: Simply type a number in the command window:

>>5
ans = 
    5

When you type the number 5 in the command window, MATLAB automatically creates a variable called ans and places it in the workspace. Note, since all MATLAB variables default to a matrix structure, technically ans is a 2D matrix. However, we will also refer to 2D arrays that contain just a single value a scalar.

If you double-click on ans in the workspace, you will open up a new window called the Variable Editor.

In the Variable Editor, you can explore the contents of any variable in the workspace. Notice that variable ans looks like a spreadsheet (because its data structure is a 2D array). Also, notice that the number 5 was automatically placed in the top left corner of this matrix. This position has an index of 1 or (1,1).

IMPORTANT: ans is a reserved name in MATLAB. You should not name any of your variables ans or you will probably get an error.

Type the number 10 in the command window:

>>10
ans =
     10

Notice how the value for ans has been replaced with the number 10, simply by typing 10 in the command window.


Naming Arrays

Top | Numeric Arrays >> Naming Arrays | Assigning Arrays | Indexing Arrays | Emptying Arrays | Transposing Arrays || MATLAB MATH

If you want to name your variable, you have to use the following syntax:

name_of_variable = value_of_variable

Type the following in the Command Window:

>>A = 5
>>a = 10

In this syntax, the equal sign = means ‘assign’, as in ‘assign the value 10 to the variable a.’ Notice that the workspace has been populated with two new variables, A and a. This is because MATLAB is case-sensitive and those two letters are treated as completely different names.

You can also assign the value from one variable to another. Try typing the following in the command window:

>> B=A

B =

     5

The variable B now has the same value as the variable A.

Remember, all MATLAB numeric variables are matrices by default. The function size, returns the array dimension size of a variable.

>>size(B)
ans =
     1     1

The result here indicates that B is a matrix with the dimensions of 1 row and 1 column. While vectors and matrices technically have different definitions, MATLAB treats them all as if they are matrices. Importantly, MATLAB cannot differentiate between a vector (1 row or 1 column) and a matrix (at least one row and one column). You need to use the function size to differentiate the two.

The function ismatrix tests whether a variable is a 2D matrix. A variable with more than 2 dimensions returns a zero. This will be important we deal with image stacks and RGB images.

Valid Array Names

Top | Numeric Arrays >> Naming Arrays | Assigning values to Arrays | Quickly Generating Arrays

You can’t just willy-nilly name your variable whatever you want. MATLAB has rules that you must follow.

Valid MATLAB variable names must start with a letter, followed by letters, digits, or underscores. They can have NO SPACES or weird characters like exclamation or hashtag. Also, MATLAB is case sensitive; recall that A and a were treated as different variables names

Name your first variable

Let’s create a new, more complex name for a variable. Type the following in the command window:

>>monkey_brains_2 = 45

Notice that in the workspace there is now a variable called monkey_brains_2 with an assigned value of 45. By using a combination of letters, numbers, and underscores, it is fairly easy to come up a diverse range of variable names. The maximum length of a variable name is the value that the function namelengthmax returns. Note the result if you type namelengthmax in the command window.

>>namelengthmax
ans = 
    63

The result (63 in this case) is longest number of characters your variable name can have, not that you will ever want a variable name that long, but it’s possible. This value varies depending on the operating system.

Avoiding Naming Conflicts

When coming up with variable names, you should try to avoid names that are already reserved by MATLAB. You can test to see if MATLAB is already using a name by using the built-in MATLAB function exist.

In the command window, type exist followed by a space and then the name in which you are interested in testing. For example, type the following in the command window:

>>exist function
ans =
     5

Since ans has a value greater than 0, then function is a reserved name used by MATLAB. In contrast, when you type the following:

>>exist monkey_brains_4
ans = 
    0

You can see that monkey_brains_4 is free for the taking since the output from exist is 0 (or false), meaning the name monkey_brains_4 is not currently being used by MATLAB.

Challenge 1

What will be the result if you type exist monkey_brain_2 in the command window? Click here to see the answer.


Assigning Arrays

Top | Numeric Arrays >> Naming Arrays | Assigning Arrays | Indexing Arrays | Emptying Arrays | Transposing Arrays || MATLAB MATH

Creating a numeric vector

Since the basic MATLAB data structure is a matrix, it is quite easy to assign an array of numbers to a numeric variable. To do so, use the following syntax.

name_of_variable = [array of numbers]

In this syntax, the square brackets ( [ ] ) are used to concatenate a collection of numbers into an array.

For example, type the following in the command window:

>>b = [1 2]

You should now see a variable called b in the workspace. Double-click on this variable to open up the variable editor:

The value 1 is stored in the top left corner position, or index (1,1), The value 2 is stored one element over in index (1,2).

Creating a numeric matrix

To add a second row to the matrix, you use the following syntax:

name_of_variable = [first row of numbers ; second row of numbers]

In this example, we use the semicolon ;. The semicolon is used to indicate a line break in a matrix or to suppress output to the command window. For example, type the following in the command window:

>>bears = [30 40; 50 60]
bears =
    30    40
    50    60

Inspecting the bears variable reveals the following matrix with two rows of data…

…with numbers in the standard index positions of (1,1), (1,2), (2,1), and (2,3).


Quickly Generating Arrays

Numeric Arrays >> Assigning values to Arrays >> Quickly Generating Arrays

The colon : indicates range and can be used to quickly fill matrices with numbers. Try typing the following commands:

>> a = 1:10
>> b = 1:2:10
>> c = [1:10 ; 11:20]

You should see the following variables in the workspace:

The variable a is filled with numbers 1 through 10. The variable b has only odd numbers up to 10. The command 1:2:10 indicates to skip every other number. Also note that c has two rows (Size: 2 X 10). To create c, we had to use the concatenating square brackets and a semi-colon. The semi-colon indicates “new row” in the array.


Challenge

What happens if you didn’t use the square brackets when assigning the variable c? What values do you think c will have? Try it now:

>>c = 1:10; 11:20

In this syntax, without using square brackets, the semi-colon indicates “new line of code”, which is the same as if you typed two separate lines of code in the command window, like this:

>>c = 1:10
>>11:20 

The end result of this syntax (either version) is the assignment of values to two variables: The variable c is assigned the values 1 through 10 and the variable ans is assigned the values 11 through 20. Why ans? Because no explicit variable was indicated in the second line of code. This is why programming is hard. Notice, we didn’t get an error, we just got something unexpected. You always have to be very careful with your syntax or you might get an unexpected result.


Indexing Arrays

Top | Numeric Arrays >> Naming Arrays | Assigning Arrays | Indexing Arrays | Emptying Arrays | Transposing Arrays || MATLAB MATH

Indexing Systems
Indexing Systems

Since all MATLAB variables are matrices, it is very easy to index a variable. You simply use the parentheses ( ) after the name of the variable. The following examples show the syntax used for linear or standard indexing:

Linear indexing

Linear indexing in MATLAB uses the COLUMN MAJOR indexing scheme, in which elements are numbered first by row, then by column.

name_of_variable(linear_index)

Standard indexing

Standard indexing requires an index for each dimension. For matrices, the first index ALWAYS refers to the row and the second ALWAYS refers to the column

name_of_variable(row_index, column_index)

Important! Indices in MATLAB always start at 1. You cannot have an index of zero. That is, zero cannot be used as an index for either method. There is no Zeroth element, zeroth row, or zeroth column. This differs from other computer programming languages, such as java or python, which start at zero.

Comparing Linear to Standard indexing

Vector indexing

To compare the two indexing methods, let’s use the variable b, which we previously assigned the following values:

>>b =
     1     3     5     7     9

When we type the following Standard indexing syntax in MATLAB, we get 3:

>>b(1,2)

ans = 
    3

When we use the Linear Indexing equivalent, we get the same result:

>>b(2)
ans = 
    3

Matrix Indexing

Things become more complicated when variables are 2D matrices. Recall that linear indexing is column major. This means that each element in the matrix is indexed first by row then by column. So, if you have more than one row of data in your matrix, you may get unexpected results if you are not careful.

For example, consider the variable bears, which has two rows and two columns:

>>bears 
ans = 
    30  40
    50  60

Linearly, the third index actually refers to the first row, second column:

>>bears(3)
ans = 
    40

Which is equivalent to a standard index of (1,2):

>>bears(1,2)
ans = 
    40

Both methods access the same element in bears.

Range Indexing

You can also use a combination of indexing and range (the colon special character) to access a range of indices in a matrix.

Consider the variable c:

If you wanted access elements 2 through 4 from the second row in the variable c using standard indexing, you would use the following syntax:

>>c(2,2:4)
ans = 
    12    13   14

Remember, for standard indexing the first number in the number pair always indicates row, while the second number (or numbers in this case) indicates columns.

If you want all the elements from the second row of a variable, you would use the colon alone, as in this syntax:

>>c(2,:)
ans =
    11    12    13    14    15    16    17    18    19    20

Notice, we have placed a colon in the column position. (2,:) translates to second row, all columns.

By comparison, linear indexing returns a different (and perhaps unexpected) result when using range.

For example, the following syntax indicates the linear indices 4 through 8. (Since there is no comma, these indices are interpreted as linear indices)

>>c(4:8)
ans =
    12     3    13     4    14

Linear indexing is column major. So, for the variable c, linear indices map to standard indices as follows:

Linear Row Column
4 2 2
5 1 3
6 2 3
7 1 4
8 2 1

Notice that when you index a variable using linear indexing, the returned result may be not preserved as a matrix structure, but be returned as a vector in a single row. For example, when we indexed c(4:8), we got a 1X5 vector. This is because we were accessible an odd number of elements from the larger array. Only even number of elements can form a 2D matrix.

TIP: For the most part, only use linear indices when you have a vector (a single row or column of data). That way, you avoid any unexpected results.

There is another major type of indexing, called logical indexing. Please refer to the content page on Logical Arrays for more information.


Challenge: Indexing with the colon

What do you think the following syntax means?

>>c(:)

What result will you get? Try it now:

Answer

Remember, the colon means “all elements” when used for indexing. Since you are only using 1 colon, you get all elements using Linear Indexing, in linear index order, which, as we have already discussed is column major. So, the end result is that you get all of the elements from c, but in the column major order (first count down the rows and then across columns).

TIP. This syntax, indexing with a single colon, is actually a very useful technique to use when you are trying to quickly reshape a matrix into a vector. You’ll see we use this syntax often, especially to simplify calculations.

Bonus challenge. What do you think this syntax returns? c(:,:). Try it now. Were you right? Can you think of a simpler syntax to use instead?


Emptying Arrays

Top | Numeric Arrays >> Naming Arrays | Assigning Arrays | Indexing Arrays | Emptying Arrays | Transposing Arrays || MATLAB MATH

Empty Entire array

You can completely empty an array by assigning to the array an empty pair of square brackets. Consider a:

>>a = 1:10
a =
     1     2     3     4     5     6     7     8     9    10


After you assign the empty brackets…

>>a = []
a =
     []

a is left an empty husk of its former self (with no values). But the variable remains in the workspace, ready to be used for later.

Similarly, if you would like to initialize an array, but give it no values, you can run the same command as follows:

>>i = []

After this command, MATLAB can recognize the variable i and fill it with content using the proper syntax.

Element deletions

If you wold like more surgical precision in your deletions, you can delete a single element from an array by using the following syntax:

>>b(3) = []
    b =
     1     3     7     9

The third element, 5, in the variable b is now gone .

Similarly, you can delete an entire column use a combination of the square brackets and indexing, as in the following syntax:

>>c(:,4) = []
c =
     1     2     3     5     6     7     8     9    10
    11    12    13    15    16    17    18    19    20

The 4th column is now removed from c.

Challenge 2

How would you delete the first row in the variable c? Answer

Warning. Be careful when trying to eliminate a single element from a matrix with more than one row of data. Doing so will automatically return a vector because all 2D matrices must have an even number of elements.

Transposing Arrays

Top | Numeric Arrays >> Naming Arrays | Assigning Arrays | Indexing Arrays | Emptying Arrays | Transposing Arrays || MATLAB MATH

Transposing interchanges the row and column index for each element. You transpose a matrix in MATLAB using the apostrophe ' using the following syntax:

name_of_variable'

For example:

>>a'
ans =
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10


MATLAB MATH

Top | Numeric Arrays | MATLAB MATH

Of course, there is no reason to fill variables with a bunch of numbers if you can’t easily manipulate those numbers using mathematical operations. In this section we will discuss using MATLAB as a calculator.

Mathematical Syntax

Top | Numeric Arrays | MATLAB MATH >> Mathematical Syntax | Array Math | Mathematical Functions

MATLAB uses fairly standard mathematical syntax:

Operation Operator Syntax Description
Addition + 4+5 4 plus 5
Subtraction 4-5 4 minus 5
Multiplication * 4*5 4 times 5
Division / 8/2 8 divided by 2
Power ^ 2^8 2 to the power of 8

Mathematical Precedence

MATLAB also uses standard mathematical operations precedence: Parentheses, Exponent, Multiplication, Division, Addition, and Subtraction (PEMDAS)

>>2 + 10 / 2
ans = 
    7
>>(2+10) / 2
ans = 
    6

Array Math

Top | Numeric Arrays | MATLAB MATH >> Mathematical Syntax | Array Math | Mathematical Functions

The nice thing about MATLAB is that you can easily apply mathematical operations to large arrays of numbers.

For example, consider x:

>> x = 1:10
x =
     1     2     3     4     5     6     7     8     9    10

To double all of the elements in x, simply multiply x by 2, as follows

>> y = x*2
y =
     2     4     6     8    10    12    14    16    18    20

To divide all of the elements in y by 4, simply use the following syntax:

>>z = y/4
z =

    0.5000    1.0000    1.5000    2.0000    2.5000    3.0000    3.5000    4.0000    4.5000    5.0000

Multiplying Matrices

Using MATLAB as a Calculator >> Multiplying Matrices | Mathematical Functions |

Matrix Product

Care must be taken when multiplying matrices. By default, MATLAB returns the matrix product (linear algebra), which may or may not be what you want, but which is definitely beyond the scope of this module.

Consider the following variables x and y:

>>x = [1 2; 3 4]
ans = 
    1     2
    3     4

>>y = [1 1; 2 2]
ans = 
    1     1
    2     2

To get the matrix product, you use the following syntax…

>>x*y
ans =
     5     5
    11    11

…and you get a result that only makes sense if you understand Linear Algebra (which, and I cannot stress this enough, we won’t get into here. So, stop worrying already).

Element-wise product

To get the element-wise product, you add a dot in front of the mathematical operation, in this case: .* . This syntax tells MATLAB to multiply each element by the corresponding element in the second array.

>>x.*y
ans =
     1     2
     6     8

This result is more intuitive. You are simply multiplying each element in variable x by the corresponding element in the variable y.

Raising a matrix to a power

The dot is also necessary when you want to raise each element in a matrix by a given power.

Element-wise power operation:

>>x.^2
ans =

     1     4
     9    16

If you don’t use the dot notation, you get a Matrix product (same as x*x)

>>x^2
ans =

     7    10
    15    22

And, actually, a matrix product has certain requirements for the number of rows and columns in each of the matrices (again, google Linear Algebra). Only square matrices can multiplied against themselves. So, more often than not, you will get an error if you try to raise a matrix to a power without using the dot notation.


Mathematical Functions

Top | Numeric Arrays | MATLAB MATH >> Mathematical Syntax | Array Math | Mathematical Functions

There are, of course, LOTS of built-in MATLAB functions that perform mathematical operations. Pretty much for anything you can think of that is math related, you should be able to find a built-in function. Search the MATLAB help for log, exp, mod, and sum. You should find a description of these functions, replete with proper syntax needed to invoke the function

Log

  • Natural logarithm: returns the natural logarithm ln(x) of each element in the input array.
>>log (2.7183)
ans=
    1.0000

>> log(1)
ans=
    0

>> log(1:10)

ans =

         0    0.6931    1.0986    1.3863    1.6094    1.7918    1.9459    2.0794    2.1972    2.3026

Exponential

  • returns the exponential e^x for each element in the input array. You can calculate the exponential for a scalar…
>> exp(1)
ans = 
    2.7183

…just as easily as for an array:

>> exp(1:10)
ans =
   1.0e+04 *
    0.0003    0.0007    0.0020    0.0055    0.0148    0.0403    0.1097    0.2981    0.8103    2.2026

Modulo Operation

The modulo operation returns the remainder after division. The function mod takes two inputs: a dividend and a divisor. It returns the remainder. So, for example, The remainder after dividing 9 by 2 is 1:

>>mod(9,2)
ans =

     1

And the remainder after dividing 8 by 2 is 0 (since 8 can evenly be divided by 2):

>>mod(8,2)

ans =

     0

As you will see in later modules, mod is a very useful function for identifying even or odd numbers.

Sum

To calculate the sum of an array, use the following syntax:

S = sum(A)

where A is an array and S is the sum returned. Let’s try it now:

>>A = 1:1000;
>>S = sum(A)
S = 
    500500

What happens if the input variable is a matrix? In this example, we will create an array called m using the function reshape (Look up reshape for more information on its syntax).

>> m = reshape(1:12,3,4)
m =
     1     4     7    10
     2     5     8    11
     3     6     9    12

m is a matrix with 3 rows and 4 columns.

What happens when we run sum on a 2D array?

>>sum(m)
ans =

     6    15    24    33

We get the sum of each column. By default, MATLAB treats 2D numeric matrices like spreadsheets and returns the results of the columns for the mathematical operation

If you want the sum all the numbers in the variable, you need to convert m into a vector first using colon indexing, as follows:

>>sum(m(:))
ans =
    78

Alternatively, you could sum up the result of the first sum. This is called a recursive call to the same function, when you input the output of a function back into that function, as such:

>>sum(sum(m))
ans = 
78

Challenge 3

Review the syntax for the function mean. How would you calculate the sum for each row? Click to see answer


Congrats! You’ve made it to the end. Module over. Back to Top


Challenge Answers

Top| Numeric Arrays | Indexing Arrays | [Using MATLAB as a Calculator][]

Challenge: Naming arrays

What will be the result if you type exist monkey_brain_2 in the command window?

ans = 

1

Back

Challenge: Indexing with Colon


c(:)
ans =

     1
    11
     2
    12
     3
    13
     4
    14
     5
    15
     6
    16
     7
    17
     8
    18
     9
    19
    10
    20

Back

Challenge: Deleting rows

c(1,:) = [];

Back

Challenge: Math with Matrices

To calculate the sum of each row of a variable, you need to include a second input into the function call of sum. This second input indicates the dimension across which you would like to sum. In this case, we would like to sum across the second dimension, as follows:

mean(m,2)

Back