CHAPTER 2

Working with Arrays

 




A major strength of MATLAB is its ability to handle collections of numbers (or other entities), called arrays, as if they were a single variable. If A and B are arrays with the same dimensions, MATLAB can add them by simply typing the typing the command: C = A + B. In most other programming languages, this operation would require several statements or commands. This capability makes MATLAB a natural choice for solving engineering and data analysis problems.

MATLAB allows you to work with several types of arrays:

  • Numeric arrays: Each element is a number (single precision or double precision, integer)
  • Character arrays: Each element is a character variable.
  • Logical arrays: Each element is a logical variable (“true” or “false” )
  • Cell arrays: Each element is another array: numeric, character or logical. Cell arrays can store different classes of arrays and are accessed by the same indexing operations as ordinary arrays.
  • Structure arrays: Each element is a structure that can store dissimilar objects (numbers, characters, logical variables) that are accessed using named fields.

In the following sections, you will learn how to:





2.1 Defining Arrays

MATLAB allows you to define several types of arrays:

  1. scalars with a single element,
  2. vectors containing ordered lists of elements,
  3. matrices with ordered elements in a rectangular arrangement.

The elements stored in the arrays may be numeric or character types. No distinction is made between integer and real numbers. The following session will show that MATLAB automatically echoes the values you set unless you end your variable definition with a semicolon.

>> s=1.2 

s = 

    1.2000     <-- s is a numeric vector with one element in it.

>> s=1.2; 

>> s 

s = 

    1.2000 

>> a='qwerty' 

a = 

    qwerty    <-- a is a character string with the characters: qwerty in it  

Since the echoing of the input value is rather verbose, you will usually want to end array definitions with a semicolon. If you forget this and start listing a very long array, simply press <CONTROL> C to terminate the listing. You will also find that MATLAB inserts blank lines to separate commands unless you instruct it to eliminate them with the command:

>> format compact 

As in the second example defining s, you can always see what a variable's value is by typing its name.

Let's define a few vectors:

>> v=[1 2 3] 

v = 

    1    2    3  <-- v is a numeric vector with three elements

>> vc=['asdf' '123'] 

vc = 

    asdf123  <-- vc is a character string with the characters: asdf123 in it

The square brackets must be used in defining numeric vectors and may be useful in constructing character arrays. A character vector (or string) consists of any linear arrangement of characters, so adding more characters takes place by direct concatenation.

Now finally, some matrices:

>> m=[1 2 3 

      4 5 6] 

m = 

    1    2    3 

    4    5    6 

>> mc=['asdf' 

       '123 '] 

mc = 

asdf 

123 

Suppose you want to see the names of the variables that you have created:

>> who

Your variables are:

a m mc s v vc

>>

These variables and their values also appear in the Workspace window, while the Command History captures the full record of this session (see illustration below).

session21


We will now introduce a simple way to define a vector of numbers of the form:
		a, a + c, a + 2c, .  . . b-c, b

where c is a constant increment. Consider for example the vector u=[ 0.0 0.5 1.0 1.5 2.0]. To put it in the previous form, we need to choose

          a=0,   c=0.5,  b=2
To define this vector, issue the following MATLAB command:
 

>>  u=0:.5:2 

t = 

        0    0.5000   1.0000    1.5000    2.0000 



We can now define other vectors quickly by performing operations with the elements of this vector:


>>  2*u 

ans = 

        0    1     2     3      4 

>>  f=sin(u) 

f = 


0 0.4794 0.8415 0.9975 0.9093


To keep track of the elements of an array, we use the row and column numbers (or array indices) of each element in an array. With the colon operator, you can select individual elements, rows, columns or "subarrays" of arrays. Consider, for example, the vector:

>> v = [1 2 3 4 5 6];

To display all the elements of the vector, issue the command:

>> x = v(:)
x =

    1
    2
    3
    4
    5
    6

To create a subvector with the 3rd, 4th and 5th elements of the vector, issue the command:

>> z= v(3:5)
z =
    3 4 5



Consider now the two-dimensional array:

M =
    1 2 3
    4 5 6
    7 8 9

To display all the elements of the third column of M, issue the command:

>> M(:,3)
ans =
    3
    6
    9

To display all the elements in the 2nd and third columns, issue the command:

>> M(:,2:3)
ans =
    2 3
    5 6
    8 9

Finally, issue the following command to create a subarray containing all the elements on the 2nd and 3rd column that also belong to the 1st and 2nd row:

>> w=M(1:2,2:3)
w =
    2 3
    5 6

You can edit the elements of an array, find the array in the Workspace window and double-click on it. The Array Editor will open in a separate window (see ilustartion below) and you can interactively change the values of any array element. Close the editor to accept the new vlues.

session22



2.2 Performing Array Operations

Array operations in MATLAB require some care. Essentially there are two types of operations involving arrays.

1) Element by element operations
2) Vector-Matrix operations.

Confusing these can lead to real difficulties. The next session shows the formation and addition of two vectors:

>> a=[1 2 3]; 

>> b=[2 5 8]; 

>> a+b 

ans = 

     3     7    11 

Now suppose we try to multiply them:

>> a*b 



??? Error using ==> * 

Inner matrix dimensions must agree. 

What happened? The multiplication symbol by itself when applied to vectors or matrices is interpreted to mean matrix multiply. We could have done this by transposing the second vector:

>> a*b' 

ans = 

    36 

 

This gave (1*2 + 2*5 + 3*8) = 36, the usual scalar product of two vectors.
If we want the element by element product, we must put a period before the multiplication symbol:

>> a.*b 

ans = 

     2    10    24 

 

The same procedure must be followed in doing division and exponentiation. For example, if you want the square of each element in a vector you must use:

>> a.^2 

ans = 

     1     4     9 

Forgetting the period will lead to:

>> a^2 



??? Error using ==> ^ 

Matrix must be square. 

The fact that MATLAB gives vector and array results with most of its built-in functions is one of its main features. The fact that sin(t), with t, a vector gives the value of sin of each element makes it trivial to look at a plot of the function.

The transpose of a matrix is found with the single quote symbol . Matrix multiplication is done with the * operator. Addition and subtraction are done with the usual operators as shown below:

>> m' 

ans = 

     1    4 

     2    5 

     3    6 

>> m*v' 

ans = 

    14 

    32 

>> m1=[6 5 4 

       7 4 1]; 

>> m+m1 

ans = 

     7    7    7 

    11    9    7 

Finally matrix division is used to solve sets of linear equations. To solve the set of equations:

	5x1 + 3x2 -  x3 =  5

	2x1 - 7x2 - 3x3 =  0

	 x1 + 5x2 + 6x3 = -7

we need to define a 3 by 3 matrix with the coefficients of the unknowns in it and divide a column vector with the right hand side coefficients by this matrix. Unfortunately you have to get used to the fact that there are two divide symbols in MATLAB.

A\B gives the solution to: A*X = B
A/B
gives the solution to: X*A = B

In our case we need to use the first form so:

>> a=[5 3 -1 

      2 -7 -3 

      1 5  6];

>> a\[5 0 -7]'   <-- Note the quote or prime to transpose the vector.

ans = 

    0.1168 

    0.8426 

   -1.8883 

 

We can confirm our solution by using matrix multiply.

 

>> a*ans 

ans = 

    5.0000 

    0.0000 

   -7.0000 

If we forget how many elements there are in a vector, the command length, will tell us. The size, command will tell how many rows and columns there are in a defined matrix. These are shown in the following session:

>> v=[1 3 5]; 

>> size(v) 

ans = 

     1     3 

>> length(v) 

ans = 

     3 




2.3 Plotting Results


The following set of commands produces a plot of sin(t) and cos(t) for t from 0 to 4pi.

>> t=0:pi/16:4*pi; 
>> plot(t,[sin(t);cos(t)]) 
>> title('sin(t) and cos(t)') 
>> xlabel('t') 
>> ylabel('sin and cos') 


Figure 2.1 Sin(t) and Cos(t)

The five lines in this sequence do the following:

1) Sets up a vector t with the elements: 0, pi/16, pi/8, .... 4pi.
2) Creates a matrix with its first row: sin(0),sin(/16),sin(/8)...sin(4). and its second row: cos(0),cos(/16),cos(/8)...cos(4). and plots the two curves.
3) Puts a title at the top of the plot.
4) Labels the x axis.
5) Labels the y axis.

If you want to save your figure to use in a later Matlab session or for someone else to see in such a session use the Save As command in the file menu on the plot figure. This will save the figure with the name you specify and an appendage of .fig. You may then retreive the file with the open command in another Matlab session.

Two three dimensional plotting routines are available. Both are demonstrated in the EXPO package. The mesh, command constructs a three dimensional plot of the values in a matrix vs the indices that specify positions in the matrix. The contour, command gives a contour plot of a matrix interpreted in the same way.

You can create up to four subplots in the same window. The first two digits in the argument of subplot, specify how many plots and their orientation as:

First Two Digits

No. of Plots

Orientation

12
Two

side by side

21
Two

above and below

22
Four

in the Quadrants


The last digit then specifies the particular plot.



2.4 Find Roots of Equations: Using Polynomial Approximations


We will demonstrate several MATLAB functions in this section. You may find them useful in solving a variety of problems, but our demonstration will show simply how to find a root of one equation. The typical problem is: find
x such that f(x)=0. Our demonstration will be concerned with finding a root of sin(x)=0. We know there are roots at 0 and all multiples of . In more complicated problems we would not know that however and might have to spend some time determining just what intervals to search for a root. Let's start by looking at a plot of our function:

>> t=0:.1:6;

>> plot(t,sin(t))

>> grid 


Try that and you can see that there is a root between 3 and 4:


Figure 2.2 Looking for a root

We could redefine t to span the interval (3,4) and plot that result to home in on the root, but will investigate using a polynomial fit of the values for our function:

>> t=3:.25:4; 

>> c=polyfit(t,sin(t),3)

c = 

    0.1537   -1.4420    3.5107    -1.5619 

>> roots(c) 

ans = 

     5.6727 

     3.1415 

     0.5704 

The polyfit, function finds a polynomial that fits the data given it in the least squares sense. In our case, it found that:

    p(t) = 0.1537t^3 - 1.4420t^2 + 3.5107t - 1.5619 


closely approximates sin(t) over the interval (3,4). The program roots finds all roots of a polynomial. We can recognize that the procedure found an answer very close to the one that we know is correct: .


2.5 Saving and Printing your Work


If you run out of time to finish a problem in MATLAB, you should save the workspace by typing:

>> save 

which produces a file called matlab.mat. This may then be retrieved by:

>> load 

when you can continue work on the problem. If you have several problems that you want separate workspaces for, simply give them different names as in:

>> save prob1 

which can be retrieved by:

>> load prob1 

If you want to start over with a fresh workspace, type:

>> clear 

If you want to get rid of only a few variables in your active workspace, give the names of the variables to be deleted after the clear, command. You can also save only a few of the variables in a named workspace by listing the names of those variables after the workspace name in the save command.

Note that when you use the save, command, you create a binary file that can not be listed or edited or otherwise used in another environment. If you have a long numeric array that you want to save so that it can be used in another environment, save that variable with the command:

>> save name.dat name -ascii

This will create a file called name.dat, with the data that was in the MATLAB variable name, stored so that it can be listed, edited or used elsewhere as any other ASCII file. It can also be loaded back into MATLAB to create the numeric array with the same data in it or with new data if the file has been edited.

Here is an example where the variable xm, is saved, then the resulting file is edited to add more data. In MATLAB the array listed as:

xm = 

 

          12          15          17          19 

           2          -3          -5         -15 

         100       10000     1000000   100000000 

It was saved by:

>> save xm.dat xm -ascii

to produce the file xm.dat that lists as:

wsname% cat xm.dat 

1.2000000e+01   1.5000000e+01   1.7000000e+01   1.9000000e+01 

2.0000000e+00  -3.0000000e+00  -5.0000000e+00  -1.5000000e+01 

1.0000000e+02   1.0000000e+04   1.0000000e+06   1.0000000e+08 

 

Suppose we edit it to add another row:

wsname% cat xm.dat 

1.2000000e+01   1.5000000e+01   1.7000000e+01   1.9000000e+01 

2.0000000e+00  -3.0000000e+00  -5.0000000e+00  -1.5000000e+01 

1.0000000e+02   1.0000000e+04   1.0000000e+06   1.0000000e+08 

   400             10.5            -18              0 

Then in MATLAB we can get this new version of the variable by:

>> clear 

>> load xm.dat 

>> format short e 

>> xm 

xm = 

1.2000e+01   1.5000e+01   1.7000e+01   1.9000e+01 

2.0000e+00  -3.0000e+00  -5.0000e+00  -1.5000e+01 

1.0000e+02   1.0000e+04   1.0000e+06   1.0000e+08 

4.0000e+02   1.0500e+01  -1.8000e+01            0 

If you want to save a copy of your session in a file for someone to study or to print, you can do so by starting the session with the diary, command. This is shown in the following example session:

>> diary mat1.t 

>> t=0:.1:6; 

>> plot(t,sin(t)^2) 



??? Error using ==> ^ 

Matrix must be square. 



>> plot(t,sin(t).^2) 

>> quit 

  183 flops 

Note the error in the squaring operation. The omitted period is one of the most common errors in MATLAB. We wanted an element by element operation on an array and must specify that.

The file mat1.t, will then list exactly like the session just shown with only the line involving diary missing. The graphics window will show your curve with axes marked at integer or simple fractions. Try the commands shown in the example session to see how simple the use of diary, and plot, is. If you save several sessions in the same file, new ones are appended. Of course, the graphics output is not saved. The recording in the file may be turned on and off with the commands:

>> diary off 

any commands that you do not want saved

>> diary on

The diary command rarely produces a file that is suitable for submission as a solution to assignments. In nearly all cases such files include rough output with numerous errors and statements out of order so that a grader can not follow what was done in completing the assignment. You should always plan to edit such files to make it clear by adding comments, reordering the output and deleting errors so that the results are easier to follow. In particular, you should show in the file the problem that is being worked and clearly designate the final answers to the problem. You may find it easier to make assignment solutions by copying the results in a Matlab session to a file that you are editing as you complete the assignment. When assignments are ready for submission, they should be stored in a file in your chbe301/chbe303 directory and clearly labeled with a name that tells what is in the file. For example, assignment 1 solution might be called solution1. When the file is ready to be graded, your TA should be sent an e-mail message telling her/him that the file is now ready for grading.


Continue on to Chapter 3
Return to Table of Contents