Data Types

Matlab knows the following data types:

  1. Matrices of floating point numbers. Vectors and scalars are special cases.
  2. Text strings. These are really vectors of characters to Matlab.
  3. Structures.
  4. Cell arrays.

Then there are more specialized datatypes such as tables.

You can also define your own data types. We will talk about that more later (see object oriented programming).

The type of a variable is not fixed.

The following is perfectly fine code (and a popular source of errors).

	a = 1;
	a = 'a string';

Vectors

To create a vector, simply fill it with values:

	a = [1, 2, 3];
	disp(a);
	1 2 3

Matlab knows row and column vectors:

	b = [1; 2; 3];
	disp(b);
	1
	2
	3
	disp(a*b);
	14

The colon operator

The colon : makes a vector of sequential numbers:

	disp(1 : 4);
	1 2 3 4
	% Now with step size 3
	disp(1 : 3 : 10);
	1 4 7 10

Indexing

To extract elements from a vector, hand it a list (vector) of indices.

>> a = [2, 3, 4, 5];
>> disp(a[1, 3]);
2 4

The vector of indices can be constructed with the colon operator:

	a = 11 : 20;  disp(a(2 : 2 : 6));
	12 14 16

Any vector can be used to index elements:

	idxV = [2 5 8];  disp(a(idxV));
	12 15 18

Then there is logical indexing.

>> a = 11 : 20; idxV = (a > 15);
>> disp(idxV)
     0     0     0     0     0     1     1     1     1     1
>> disp(a(idxV))
    16    17    18    19    20

See also the find function for a similar idea.

Exercises

Start with x = 1 : 3 : 30.

  1. Find all even elements.
  2. Find all elements between 5 and 20.
  3. Set all even elements to their negative values.

Matrices

A matrix is an n-dimensional array of numbers. One can also have arrays of other data types (see cell arrays).

To create a matrix, simply fill it with values.

	a = [1 2 3; 4 5 6];  disp(a);
	1 2 3
	4 5 6

Many commands work directly on matrices.

	a = [1 2 3]; b = [2; 1; 1]; disp(a * b);
	7
	disp(b * a);
	2 4 6
	1 2 3
	1 2 3

To extract elements:

	c = b*a;  disp(c(1:2, 2:3));
	4 6
	2 3

To extract all elements:

	disp(c(1,:));
	2 4 6

But note: c(:) yields all elements flattened into a vector!

	disp(c(:)');
	2 1 1 4 2 2 6 3 3

To extract a list of elements, use sub2ind.

c = [1 2 3; 4 5 6];
idxV = sub2ind(size(c), [1,2], [2,3]);
>> c(idxV)

ans =

     2     6

>> disp([c(1,2), c(2,3)])
     2     6

Matrix Pitfalls

Incorrect Indexing

	c = [1 2 3; 4 5 6]; disp(c(5))
	3

c(5) should be a syntax error, but instead yields the 5th element of the flattened c(:) matrix!

Matrix dimensions change when you add elements.

>> x=1;
>> x(2,2) = 2

x =

     1     0
     0     2

This is a common source of bugs and one of the most counterproductive features of Matlab.

Multi-dimensional matrices

Matlab matrices can have more than 2 dimensions.

	a = rand([3,2,5]); 
	size(a)
	ans =
	3     2     5

	a(:,:,3)
	ans =
	0.9218    0.4057
	0.7382    0.9355
	0.1763    0.9169

Sub-matrices work just like ordinary 2-dimensional matrices.

But: a(:,1,:) is not a 2D matrix. It’s a 3D matrix with a singleton 2nd dimension.

Matrix Exercises

  1. Construct a matrix A with elements [2,4,...,20] in row 1 and [1,4,7,...,28] in row 2.
  2. Replace row 1 with its square.
  3. Find all columns where row 1 > row 2.
  4. Let x=ones(10,1). Compute Ax.

Structures

Structures are containers for variables of different types.

They are defined by simply adding element to a blank structure.

Example:

Store the contact information for a person.

	contactS.Name = 'John Doe';
	contactS.Age = 37;

The elements are accessed by name:

	disp(contactS.Age);
	37

One can have structure arrays, but they are tricky because each element must be a structure with the same fields.

Often, cell arrays are more useful.

Where structures are useful

Use a structure to pass a large number of arguments to a function.

  • Example: Set of parameters and prices for solving a household problem.
  • Example: Our models store all fixed parameters in a structure that is passed to essentially all functions.

Structures can make code robust against changes.

  • Example: Add a preference parameter to the model. Only the household code needs to be changed. Other programs use the same structure to look up model parameters.

Text Strings

To Matlab, a text string is a vector of characters. And a character is represented by a number.

Therefore: most vector operations work on text strings.

Example:

myName = 'Hendricks'; disp(myName(5:8));
rick
disp(myName(5) == 'r');
1

sprintf

sprintf produces formatted text from (usually) numerical inputs.

The syntax is almost the same as in C. Read the manual for details.

Example:

	sprintf('Integer: %i. Float: %5.2f. String: %s', 5, 3.71, 'test')
	ans =
	Integer: 5. Float: 3.71. String: test

Cell Arrays

A cell array is an n-dimensional array of mixed data.

Each cell can hold a different data type.

>> x = {'abc', 17; [3,4,5], {1, 2}}
x = 
    'abc'           [      17]
    [1x3 double]    {1x2 cell}
>> disp(x{1,1})
abc
>> disp(x{2,1})
     3     4     5

Uses:

  • most common: replacement for structure array when one is not sure that all elements have the same fields.

Numeric Precision

By default, numeric variables are stored as double (double precision float, 64 bit).

Even if you define x=1, it is a double.

>> x=1;
>> class(x)

ans =

double

If you work with large (simulated) datasets, you may want to store matrices in formats that take less storage.

>> x = ones([1,3], 'uint8')

x =

    1    1    1

This leads to some nice opportunities for errors about which Matlab helpfully does not complain (another Matlab bug).

>> x(2)=1e5

x =

    1  255    1

The number assigned to x was too large for an 8 bit integer. It gets truncated without warning.

Worse, applying common numeric operations to integers returns integers:

>> y = x/2

y =

    1  128    1

>> class(y)

ans =

uint8
Rule of thumb: Store large datsets in low precision. Make everything double the moment you load it.