Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB Programming Basics Copyright © Software Carpentry 2011

Similar presentations


Presentation on theme: "MATLAB Programming Basics Copyright © Software Carpentry 2011"— Presentation transcript:

1 MATLAB Programming Basics Copyright © Software Carpentry 2011
Hello, and welcome to the Software Carpentry Episode on MATLAB programming. In this episode, we will cover the array data type, which is the primary data type in MATLAB. Copyright © Software Carpentry 2011 This work is licensed under the Creative Commons Attribution License See for more information. 1

2 MATLAB (http://www.mathworks.com)
Facilitates programming problems that require a lot of matrices… And many other things A data parallel programming model – Write x*A*x’ to calculate xAxT – The computer takes care of the loops All encapsulated in special objects called arrays MATLAB was originally designed to provide an easy way to manipulate matrices. If you’ve ever tried to use an array of arrays to store a matrix, you know how many loops are required to write even simple programs. MATLAB performs those loops for you, so you can write “x times A times x transpose” rather than writing matrix – vector multiplication functions.

3 MATLAB arrays are the main data structure in MATLAB.
They consist of several variables of the same type, which is usually a double precision, floating point number. They can have one or more dimensions. They can be created, reshaped, indexed, and combined in many ways that we will see below. You’ll hear the terms array and matrix used interchangeably. The main data structure in MATLAB is an array of double precision, floating point numbers. Arrays can have one or more dimensions, and they can be manipulated and combined in many ways that we will cover in subsequent lectures. Many applications utilize two dimensional arrays as matrices, so you’ll hear us use the terms array and matrix interchangeably. However, if we say matrix, we always mean an array with 2 dimensions. 3

4 A semi-colon denotes a row boundary
Create an array from numbers: >> a = [1 2 ; 3 4]; >> a 1 2 3 4 What would “a = [ ]” give you? What about “a = [1; 2; 3; 4]”? A semi-colon denotes a row boundary Columns are delimited by spaces or commas. Arrays can be created from the MATLAB prompt. When you assign an array, the entire set of numbers is enclosed in brackets. Elements in the same row are separated by spaces or commas and a semi-colon denotes a row boundary. Just like in linear algebra, a row array is different from a column array.

5 Create an array from other arrays: >> b = [a a] b 1 2 1 2
Sometimes, this is called a block matrix. Sometimes, it is helpful to create a block array by using other arrays rather than scalars in the definition. This is fine as long as the sizes of the arrays match up.

6 Create an array from other arrays: >> b = [a a] b 1 2 1 2
>> b = [b 1]; ERROR! Sometimes, this is called a block matrix. In this case, we tried to combine a 2 by 4 matrix with a scalar, which is the same as a 1 by 1 matrix. MATLAB will not allow this.

7 Create special arrays: >> z = zeros(2,3);
>> o = ones(3,2); >> e = eye(2,2); % That’s the identity matrix, get it! >> r = rand(2,3); The semi-colon tells MATLAB to suppress output. There are other ways to make matrices. The functions zeros and ones will create matrices that have all ones or all zeros. Another special function is eye, which creates an identity matrix. Finally, rand creates a matrix of random doubles between zero and one.

8 There are also many functions to operate on arrays.
Data-parallel programming tip: it is better to pass an array to a function and have it operate on each element than to pass each element individually. Several functions can be used to examine the shape and type of an array. In a later episode, we will talk about how to program your own functions, but for now, let’s explore some of the built in functions to examine the shape and type of an array. 8

9 All operators act on arrays: >> a + a ans = 2 4 6 8
2 4 6 8 >> a * a What would * do for a 3-dimensional array? The simplest functions are arithmetic operators, which operate on arrays in the way you would expect for matrices and vectors. Addition is elementwise and assumes that the two arrays have the same size.

10 All operators act on arrays: >> a + a ans = 2 4 6 8
2 4 6 8 >> a * a What would * do for a 3-dimensional array? Usually, we’ll ignore this line when we post output. Don’t be alarmed if you see it in your MATLAB session. Multiplication is matrix multiplication and assume that the inner dimensions agree. As an exercise, see if you can figure out what happens when you multiple two 3 dimensional arrays. As a hint, try to see what sizes must match between the arrays.

11 Other important operators: >> a’ Transpose the array
If b is square: >> a / b Equivalent to a * inv(b) If a is square: >> a \ b Equivalent to inv(a) * b inv() is the inverse function for a matrix. More on that later. Other important operator are the transpose operator, which is a single quote, and two kinds of division. The first division a forward slash, is equivalent to a divided by b if a and b are scalars. If they are arrays, it is equivalent to a times the inverse of b. As a convenience, MATLAB provides a backslash division, which is inverse of forward slash. 11

12 a(1,1)b(1,1) a(1,2)b(1,2) a(1,3)b(1,3) a(2,1)b(2,1) a(2,2)b(2,2)
Operators can also be made to act element wise with a dot: >> a .* b What does a .\ b do? Try to figure out what it will do, then test yourself in MATLAB. a(1,1)b(1,1) a(1,2)b(1,2) a(1,3)b(1,3) a(2,1)b(2,1) a(2,2)b(2,2) a(2,3)b(2,3) a(3,1)b(3,1) a(3,2)b(3,2) a(3,3)b(3,3) Rather than loop through each element of two arrays to combine them elementwise, most operators can be made to perform elementwise operations by putting a period before the operator. For instance, a dot times b is returns the elementwise product of a and b. Do you see how this might help the programmer avoid writing a loop? 12

13 >> reshape(a,[4 1]); Resize array into a column vector
Two ways to reshape: >> reshape(a,[4 1]); Resize array into a column vector >> b = a(:); Same thing: make a into a column vector. >> b 1 3 2 4 Arrays can also be reshaped using two methods. The first is the function reshape. The first parameter to reshape is the array you want to reshape while the second is a vector of dimension sizes. In this case, we want to transform a in to a vector with 4 rows and 1 column. Since vectorizing an array is such a popular operation, there is n equivalent shortcut called a colon. 13

14 What if we want a 2x3x? array?
Reshape reexamined… Let B be a 3x4x5 array. That’s 60 elements. What if we want a 2x3x? array? 2x3x10 = 60, so ? = 10… If B is a 3 by 4 by 5 array then it has 60 elements. We want to transform it to a 2 by 3 by something array, and it isn’t too hard to see that the third dimension must be of size 10. What if we don’t want to compute the extra dimensions every time? 14

15 Or MATLAB can figure out the third parameter:
>> B2 = reshape(B,2,3,[]); We used multiple parameters instead of an array. We pass [] for the parameter that should be figured out. Just be sure that there is a shape that works: >> B3 = reshape(B,7,2,[]) Error: 60 is not a multiple of 14. It turns out MATLAB can compute a single missing dimension in reshape. In this case, we pass each dimension size as a separate parameter. This is fine for reshape. For the last size, we put in a pair of empty brackets, which is a sign to MATLAB to figure out that dimension for us. The reshape function will not add or delete elements from an array, so if the first two dimension sizes make it impossible to define an array, MATLAB is going to complain 15

16 But computer memory is 1-dimensional Must decide how to lay out values
Key question: in what order does reshape consider elements? >>> A A looks 2-dimensional But computer memory is 1-dimensional Must decide how to lay out values Another important consideration is the order that reshape lists its elements. In order to answer this question, we need to explore a little bit about how the computer stores a matrix. When we see a matrix, we think about a two dimensional set of memory locations that each hold a number. The problem is that computer memory is 1-dimensional. In fact, it is one long array. To think about two dimensional matrices, we need to decide on a convention on how store the matrix in memory. 16

17 Used by C and Python Row-major order concatenates the rows Logical
1 2 3 4 5 6 7 8 Logical One possibility is row-major order, which concatenates the rows. This is the convention used in the C programming language and in Python, since Python is written in C. 1 2 3 4 5 6 7 8 Physical 17

18 Used by Fortran and MATLAB
Column-major order concatenates the columns Used by Fortran and MATLAB 1 2 3 4 5 6 7 8 Logical In contrast, column-major order concatenates the columns. The Fortran language uses column-major order, and since MATLAB uses many matrix manipulation programs in from Fortran, MATLAB uses the column-major ordering. 1 5 2 6 3 7 4 8 Physical 18

19 No difference in usability or performance…
…but causes headaches when passing data from one language to another (Just like 0-based vs. 1-based indexing) In what order are 3-dimensional arrays stored? As an exercise, see if you can guess how the two types of languages store 3-dimensional or higher-dimensional data. 19

20 No difference in usability or performance…
…but causes headaches when passing data from one language to another (Just like 0-based vs. 1-based indexing) What order are 3-dimensional arrays stored in? reshape always pulls elements in the order they are stored: column major order. It turns out that reshape always fills the new shape by pulling elements in the order in which they are stored. Since in MATLAB this is column major order, reshape fills the new array by pulling elements from column 1, then column 2, and so on. 20

21 Arrays are dynamically resized: >> a(3,3) = 1 1 2 0 3 4 0 0 0 1
What would this do: >> b = 1; >> b = [b 1]; Array can also be dynamically resized. If an element is assigned beyond the bounds of the current array, the array is filled with zeros for all spots that need to be created. Keep this in mind if you assign a zero to, say, the millionth column of an array: MATLAB is going to create 1 million columns of zeros in order to have space for the new element. 21

22 What really happens when an array is resized?
MATLAB has to allocate a new chunk of memory to hold the array The array is copied to the new memory, with zeros filling the empty spaces. Continuously resizing an array is expensive, so it’s best to initialize an array using >> a = zeros(s1,s2,…) to the largest size that will be needed. Remember that an array is stored in column-major order. If an array is resized in a way that changes the size of the columns, then the ordering is destroyed. A whole new block of memory gets allocated to hold the array, then the existing values are copied to new the memory locaiton. If we continuously add elements to the end of an array, like on the last slide, the overhead can be very expensive. That is why it is better to initialize an array to the size you know you will need then go back and fill the array one slot at a time. 22

23 Arrays are blocks of homogeneous data
Review: Arrays are blocks of homogeneous data They operate like arrays under the standard operations +,-,*. MATLAB provides many methods to work with arrays Reshape Resize To review, in MATLAB, the primary data type is the multidimensional array of double precision floating point numbers. All of the arithmetic operations operate directly on arrays, and MATLAB provides hundreds of functions that also operate on arrays. Among those functions are reshape and implicit resizing. We’ll see many more operations in the coming episodes, including a rich library of visualization functions.

24 Richard T. Guy created by February 2011
In the next episode, we'll have a look at how we can select values from arrays using indexes. February 2011 Copyright © Software Carpentry 2011 This work is licensed under the Creative Commons Attribution License See for more information. 24


Download ppt "MATLAB Programming Basics Copyright © Software Carpentry 2011"

Similar presentations


Ads by Google