mathcad worksheet 8

18
Example Sheet 8 – Doing more with arrays and using Range Variables The aim of this worksheet is to introduce you to more things you can do with vectors and matrices in MathCAD. By the end of the sheet you will know how to: Create vectors and matrices Perform simple matrix and vector mathematics Access individual elements of arrays Access columns and submatrices within arrays Create and use range variables Use range variables to create vectors and matrices Read in data to analyse from a file. This worksheet takes the form of a number of examples which illustrate and introduce these principles. Work through them all. Exercise 1 – Creating vectors and matrices and doing simple maths with them In this exercise we will create some vectors and matrices, which will then form the basis for our later investigations. Start MathCAD and create a new, blank worksheet Display the Matrix Toolbar by selecting View|Toolbars| Matrix from the menu Use the [:::] button on the matrix toolbar to create the following matrices: o The vectors VA and VB are defined with 2 rows and 1 column o The matrices MA and MB are defined with 2 rows and 2 columns © DPL 2002,3,5 1/18

Upload: bolarinwa

Post on 12-Jan-2016

45 views

Category:

Documents


0 download

DESCRIPTION

Mathcad Worksheet

TRANSCRIPT

Page 1: Mathcad Worksheet 8

Example Sheet 8 – Doing more with arrays and using Range Variables

The aim of this worksheet is to introduce you to more things you can do with vectors and matrices in MathCAD.By the end of the sheet you will know how to:

Create vectors and matrices Perform simple matrix and vector mathematics Access individual elements of arrays Access columns and submatrices within arrays Create and use range variables Use range variables to create vectors and matrices Read in data to analyse from a file.

This worksheet takes the form of a number of examples which illustrate and introduce these principles. Work through them all.

Exercise 1 – Creating vectors and matrices and doing simple maths with themIn this exercise we will create some vectors and matrices, which will then form the basis for our later investigations.

Start MathCAD and create a new, blank worksheet Display the Matrix Toolbar by selecting View|Toolbars|Matrix from the menu Use the [:::] button on the matrix toolbar to create the following matrices:

o The vectors VA and VB are defined with 2 rows and 1 columno The matrices MA and MB are defined with 2 rows and 2 columns

Having created these arrays, we can use them to perform simple matrix maths.

Vectors and matrices may be added or subtracted, if they are of the same size.

© DPL 2002,3,5 1/14

Page 2: Mathcad Worksheet 8

MathCAD enforces rules of matrix maths and will not allow addition of matrices or vectors of different sizes.

MathCAD will allow addition or multiplication of an array by a scalar. In this case the scalar is added or multiplied by each element of the matrix in turn:

MathCAD will also calculate the dot products of vectors and matrices, providing the inner dimensions are compatible…

The ‘dot’ operator for matrix multiplication is the same ‘*’ as is used for conventional multiplication, alternatively you can select the ‘dot product’ operator from the matrix toolbar.For practice, create the following arrays and matrices:

© DPL 2002,3,5 2/14

The number of rows and/or columnsin these arrays do not match

Page 3: Mathcad Worksheet 8

Exercise 2 – Accessing parts of Arrays

In the last exercise we applied operators (such as addition and multiplication) to entire arrays. In this exercise we will see how to access individual elements or parts of arrays by using indices.

MathCAD, by default, starts counting with indices at 0, so the first element of an array is at index 0. This can be changed but I would strongly advise against doing so.

MathCAD uses array subscripts to address individual elements of an array. Array subscripts may be created either by selecting the subscript operator from the matrix toolbar or by using the <[> key.

We will use the arrays you defined in the last exercise to practice on.

Using these arrays, we will first use subscripts to extract values from the arrays and then use subscripts to set individual elements of the array.

© DPL 2002,3,5 3/14

Page 4: Mathcad Worksheet 8

On the worksheet you have been using so far, position the cursor below the last matrix definition.

Type VA[0= MathCAD responds by giving the value of the ‘zeroth’ element of the vector VA In the same way, query the value of VA1 by typing VA[1= The two values should be displayed as shown.

For two dimensional arrays, (matrices), mathCAD uses 2 indices separated by a comma, in the order Row,Column

We can use the same subscript operator to set individual elements of arrays. To do this, simply follow the expression which references the array with the assignment operator <:>

For example, to set value of the zeroth element of VB to 7, type VB[0:7

© DPL 2002,3,5 4/14

Page 5: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Exercise 3 – Accessing parts of arrays

As well as using the matrix indices to access individual elements of an array, we can use functions to access a subset of the matrix containing several elements. We met this operator earlier when we used it to separate out different parts of experimental data.

MathCAD has an operator to access an entire column of a matrix at one time. It is shown on the worksheet as shown below

To insert the row operator into your worksheet, you can either select it from the matrix toolbar or type <ctrl-6> from the keyboard. The ability to extract a column from a matrix is particularly useful when reading experimental data from a file into mathCAD, as we will see later.

MathCAD also has a function, submatrix(), which can extract a number of rows and columns from an array

© DPL 2002,3,5 5/14

Page 6: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

As an exercise, use the functions and operators to print out the following parts of the arrays:

The zeroth column of array MAThe first column of array MBThe zeroth and first row of matrix MCThe 2x2 submatrix at the bottom right hand corner of matrix MDThe submatrix with 2 columns and 3 rows at the bottom right hand corner of ME

Transposing Rows and ColumnsAnother operator which works with arrays is the transpose operator (MT). This can be found on the matrix toolbar and swaps the rows and columns of a matrix.You can use the transpose operator in conjunction with the column select operator to extract a single row from a matrix. The examples below show the transpose operator in action.

© DPL 2002,3,5 6/14

Page 7: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Exercise 4 – Other matrix functions and operators

There are many other functions which operate on vectors and matrices. Some of these may be found on the matrix toolbar and others can be found on the functions dialog box (from the f(x) toolbar button) under the heading “Vector and Matrix”.

I have given brief notes on some of the important ones below. In the summary I have followed the MathCAD convention of using V to refer to a vector function, M to refer to a matrix function and A to refer to an array, which can be either a vector or a matrix.

rows(M), cols(M) Return the number of rows and columns in matrix M.min(A), max(A) Return the minimum or maximum value in array A.last(V) Returns the index of the last element of Vlength(V) Returns the number of elements in Vmatrix(r,c,F) Returns a matrix with r rows and c columns using the function F. stack(A,B) Returns the result of putting matrix A on top of B. A & B must

have the same number of columnsaugment(A,B) Returns the result of placing matrix B to the right of matrix Aidentity(n) Returns the identity matrix with n rows and n columnsV Sums the elements in the vector V – from toolbar

The following sorting functions work on arrays and vectors and may be found under the “sorting” heading of function dialog box

sort(V) Sorts a vector V into ascending order reverse(A) Reverses the elements of a vector or the rows of an arrayrsort(M,n) Arranges the columns of M until row n is in ascending ordercsort(M,n) Arranges the rows of M until column n is in ascending order

Experiment with the using these functions on your example vectors and matrices to solve the following problems:

What is the largest element in matrix ME ? What is the smallest element in matrix MC ? What is the smallest element in column 1 of matrix MD ? What is the largest element in row 2 of matrix MD ? Combine matrices MD & ME and sort the result to produce a matrix with 7 rows

and 3 columns with column 0 in ascending order.

© DPL 2002,3,5 7/14

Page 8: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Element by element evaluation with the Vectorise operator

The determinant operator (|M|) can be used to return the determinant of a matrix. We can also use the same operator to return the absolute value of a number.

Suppose that instead of wanting to find the determinant of a matrix we wish to find the absolute value of all the elements in the matrix. In order to do this we use the vectorise operator from the matrix toolbar. This is shown as an arrow over f(M).

In the example on the left, the determinant operator is applied to the 2x2 matrix and calculates the determinant as normal. In the example on the right, the vectorise operator has been applied to the determinant operator, causing it to be applied to each element of the matrix in turn.

The vectorise operator also works with matrix multiplication, as shown below:

In the left hand case, two vectors are multiplied together using the normal rules of matrix multiplication, giving a scalar product. In the right hand case the vectorise operator forces the multiplication to take place on an element by element basis.

The vectorise operator works for all operations that normally have a special meaning for matrices.

Exercise 5 – Range Variables and filling matrices

Up until now, all the variables you have used in mathCAD have taken a single value (or set of values in the case of arrays). A range variable is a special type of variable which takes on a whole series of values, any expression involving the range variable is evaluated a number of times, once for each value in the series.

Because range variables take on a series of values, mathCAD places restrictions on where they may be used, if you attempt to use a range variable in the wrong place, mathCAD

© DPL 2002,3,5 8/14

Page 9: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

will highlight the offending expression in red and the error message will refer to ‘Illegal Context’.

Range values correspond to FOR loops in conventional programming languages, and are very useful when used with arrays to identify elements of the array.

To start with, we will create a range variable, i, and do some experiments with it.

Start with a fresh mathCAD sheet. Define the range variable by typing [i][:][0][;][3] Notice how you define the range variable by typing the semi-colon character [;]

and mathCAD displays this as a series of dots. Once you have defined the range variable, you an ask mathCAD to print out the

value of it, like you would any other variable, by typing [i][=] In this case, however, mathCAD prints a table of values. Your sheet should now look like this:

Notice how the display of the values of I is subtly different from the way in which mathCAD displays a matrix or a vector.

You can create an expression involving the range variable and mathCAD will evaluate the expression for each of the values taken by the range variable. In the example below I have asked mathCAD to do evaluate a number of expressions involving the range variable.

Again, you should note that mathCAD is simply displaying the result of a calculation repeated a number of times, changing the value of i each time.

© DPL 2002,3,5 9/14

Page 10: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Range variables find their greatest use when filling an array with a set of values.

Suppose that we were performing an experiment where we took a reading every 10 minutes. We could create an array and type the times into it by hand, like this:

But this is tedious and prone to mistakes, especially if we had 100 times to type in instead of the 4 in this case.

Looking at the series of numbers in the array, we can say that the i'th element is i times 10 minutes, which we express to mathCAD like this:

Note how the range variable on the left hand side of the assignment symbol is used to index through the array elements while the same variable on the right hand side is used to create their values. For practice, after you have created the ‘time’ array, have a go at creating the following arrays using range variables:

The array ‘evens’, which contains the first 5 even numbers. The array ‘odds’ which contains the first 5 odd numbers The array ‘squares’ which contains the squares of the first 6 integers.

When you have finished, your arrays should look like this:

© DPL 2002,3,5 10/14

Page 11: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Exercise 6 – Statistical functions and arraysMathCAD has a range of statistical and related functions which operate on arrays.

As a simple example, we are going to perform some statistical analysis on a series of results. These can be placed into a vector and the mean and standard deviation calculated:

The mean and stdev functions may be selected from the f(x) dialog box, under the function category ‘statistics’.

Note that you can add units to a vector. If all elements of a vector have the same units, the easiest way to do this is to select the entire matrix and multiply it by the appropriate unit. The units will then propagate through to the answers as shown below:

© DPL 2002,3,5 11/14

Page 12: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

© DPL 2002,3,5 12/14

Page 13: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Exercise 7 – Getting data from a file.

Although for simple experiments it is possible to type values directly into MathCAD using an input table, frequently we have to process sets of results that come from computer controlled test and measurement equipment, or that have been tabulated by other researchers. MathCAD can read data files stored on the computer and bring those into its calculations.

As an exercise, I have prepared two files for you to bring into MathCAD and perform some simple analysis upon. The files are data taken from one of my detector experiments. The first column shows the detector number, and the second column the number of counts received on each detector over a 10 second period. The two files are nominally from the same spectrum but shifted along the array.

Use a web browser to bring up the page http://users.aber.ac.uk/dpl/ph15720/handouts/handouts.htm and at the bottom of the page you should see a link to datafiles for exercise 8. Right click on the link and save the first file on your M: drive with your other MathCAD files, use the default filename of detectordata.txt. Repeat to save the second file in the same place, with the default filename of detectordata2.txt. Once the files have finished downloading, close the browser and return to MathCAD.

On a blank MathCAD worksheet, select “Insert|Component…” from the menu. This will bring up a wizard where you should first indicate that you want to read data from a file. On the next page of the dialog box you should leave the file type as ‘Text File’ and use the browse button to locate the datafile you have stored on your M: drive in the previous step. Once the wizard closes, your worksheet should show an icon representing a file read component, with a little disk on it. The cursor will be positioned in a placeholder ready to hold the name you wish to give the dataset. Once you have given it a name your worksheet should look like this:

Now, using the techniques we started to explore with the resistor experiment and the photoelectric effect, carry out the following analyses on the data. I have put some hints at the bottom of the page which may help if you get stuck.

From the matrix of data, create a vector to hold the Detector number and another to hold the counts.

Plot the counts against detector number.

© DPL 2002,3,5 13/14

Page 14: Mathcad Worksheet 8

PH15720 MathCAD Example Sheet 8

Create a plot of count rate vs detector, given that the sample period was 10 seconds.

Each detector is 20um x 2mm. Produce another graph with the plot rate scaled in terms of counts per second per cm2.

There are 2 clear peaks in the data. Find the height of the largest peak in terms of counts per second.

Create an expression which will give the number of the detector with the highest counts.

Use the submatrix function to create a matrix containing the data from the highest counting channel together with the 6 channels on either side.

Calculate the total number of counts in the highest peak and its adjacent channels that you have just created above.

Create a function called PeakArea which takes as its arguments the channel number and the width of the peak in channels. It is to return the total number of counts of the given channel together with those up to 1 width away. For example, PeakArea(42,3) will give the total counts from detectors 39,40,41,42,43,44 and 45.

Use the PeakArea function to re-calculate the area of the highest peak and the 6 channels either side.

Create a graph which will show the largest peak and a specified number of adjacent channels on either side.

Go back to the file read component and right click on it, select “Choose File…” from the pop-up menu and pick the file “DetectorData2.txt”. Click out of the file read component and check that all of your answers and graphs change to reflect the new data file.

HintsThe following hints may be useful to you. Use the help system and conduct some experiments with MathCAD to see how.

You may want to create a unit for the micron (1 um is 10-6 m)The max() function will tell you the largest number in a vectorThe csort() function can be used to sort a matrix so that a particular column is in ascending order.You can reverse() the results of a sort.You can use variables in the placeholders which determine the axis scaling of a graph.The submatrix() function can be used to pick off part of a matrix.The matrix toolbar has one way of summing the elements of a vector.The calculus toolbar has two more ways of doing summations.

END

© DPL 2002,3,5 14/14