程序代写代做代考 matlab algorithm Chapter 1

Chapter 1
Performing calculations in MATLAB
In this chapter we’ll learn how to perform calculations with MATLAB. First we’ll learn how to use it as a sort of advanced calculator. Next we’ll see how to use it to perform some linear algebra calculations. Then we’ll take a look at how to use it for some simple stochastic simulations. We’ll be able to do quite a lot with only a very little MATLAB knowledge.
1.1 MATLAB’s user interface
When you 􏺉rst open MATLAB the screen should look something like the schematic diagram shown in Figure 1.1:
The main part of the screen to focus on is the so-called Command Win- dow. This is where you type commands that you want MATLAB to act on immediately.
For example you can enter the command:
and MATLAB will create a variable called a and assign it the value 3. It will also print out a message to indicate what it has done. In this case it simply reports that a = 3.
1
Tip: Obtaining MATLAB
While you are a student at King’s you can obtain MATLAB using the following link https://internal.kcl.ac.uk/it/software/matlab.aspx.
a=3

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 2
Figure 1.1: The layout of the MATLAB User Interface
Similarly we can create a variable called b and assign it the value 2 by entering:
If you now enter the command:
Matlab should report that the answer is 5.
If you now look over in the Workspace window you will see all the variables
that you have created. These are a, b and a temporary variable called ans which is used to store the result of the last computation.
If you look over at the Command History window, you will see a record of all the commands that you have entered. You can use the command history to easily rerun commands.
An alternative method is to press the up and down arrows in the Command Window. Try doing this now to run the calculation of a + b a second time.
You can change the values of any variable if you like for example by entering
MATLAB even understands the statement
b=2
a+b
a = b + 25

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 3
This is how you say 􏺆add one to the variable a􏺊 in the MATLAB language. Naturally you are not restricted to adding numbers. You can use * to multi- ply numbers, / to divide them, – to substract them, ^ to raise one to the power
of another. In addition you can use brackets to group terms together.
You can also use the standard functions that you might expect such as sin, cos, sqrt, exp log. You should use brackets when you call a function. Here’s
an example:
1.2 Exercises
Experiment with the MATLAB command window to answer the following ques- tions
1) What is the cube root of 2?
2) Does sin use degrees or radian’s?
3) What base is used for logarithms using the log command?
4) What happens if you forget the brackets and type log 1?
5) What happens if you type a+1=a instead of a=a+1?
6) Use the up arrow to run the command a=a+1 repeatedly. Check that it is doing what you expect.
7) Work out how to compute 10 factorial using the help if you can’t guess. 1.3 Matrices in MATLAB
1.3.1 Matrix basics
The name MATLAB actually stands for 􏺆Matrix laboratory􏺊 and not 􏺆Maths laboratory􏺊. So you might expect it makes working with matrices very easy.
a=a+1
sin( 360 ) ans =
0.9589

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 4
To store the 3 × 3 matrix:
245 −3 1 7 492
in a variable called a you use the following command:
Note that spaces are used to separate columns and semi-colons are used to separate the rows. If you aren’t sure what a semi-colon is, see table 1.1
So we can create two 1 × 3 row vectors v1 and v2 as follows:
and a 3 × 1 column vectors w1 and w2 as follows:
Performing matrix operations is just as easy as performing normal calcula- tions for example to multiply a and w1 just enter
or to add w1 and w2 just enter
The operators – and ^ work as you expect too. For example you can use ^2 to square a matrix.
What about division? Well division of matrices isn’t a standard mathemati- cal operation, so you can’t simply divide matrices. However, to invert a matrix you can use the function inv (raising it to the power −1 works too, but may be slower and less accurate since the function inv will have been optimized for computing inverses).
MATLAB uses the division operator \ for solving matrix equations – which is the matrix analog of division. But since matrix multiplication is non-commutative MATLAB makes a distinction between between dividing matrices on the right and dividing on the left. For example, suppose we want to solve the matrix
a = [ 2 4 5 ; -3 1 7 ; 4 9 2 ]
v1 = [ 1 2 3 ] v2 = [ 4 5 6 ]
w1 = [1; 2; 3 ] w2 = [4; 5; 6 ]
a * w1
w1 + w2

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 5
equation Av = w where v and w are vectors and A is a matrix. Then the solution is v = A−1w, which requires us 􏺆to divide w by A on the left􏺊. In MATLABonecanwritev = A\ wtomean􏺆letvbethesolutionofAv=w. If you wanted to solve the equation vA = w where v and w are row vectors, you would write v = w / A but this is less common.
Another common function with matrices is to compute the conjugate trans- pose, also known as the adjoint of the matrix. For the real valued matrices we’ll use in this course, the conjugate transpose is the same thing as the trans- pose. To compute the conjugate transpose in MATLAB you use the apostrophe symbol ‘. For example, here is how you compute the transpose of v1
It is quite normal to create column vectors by creating a row vector and then taking its transpose. Here is how we could have initialized the vectors w1 and w2:
1.3.2 Creating matrices
As you have probably already found, entering a matrix by hand is quite a boring task. So MATLAB provides several functions to quickly create matrices with given values. Here are some functions that we will use a lot:
􏺐 zeros Create a matrix which consists only of zeros.
􏺐 ones Create a matrix consisting only of ones.
􏺐 rand Create a matrix containing random numbers uniformly distributed.
􏺐 randn Create a matrix containing random numbers which are normally distributed.
You use all of these functions in similar ways. To 4 × 6 matrix of zeros you would type:
To create a 3 × 5 matrix of random numbers between 0 and 1 you would type:
v1′
w1 = [1 2 3 ]’ w2 = [4 5 6 ]’
zeros (4 ,6)
rand (3 ,5)

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 6
Table 1.1: Some English words for punctuation marks
In computer programs punctuation is very important. Many non-native English speakers are unfamiliar with the names for the di􏺈erent punctuation marks used in programming. For their bene􏺉t, here is a guide:
Symbol
Term
. Full stop or just 􏺆dot􏺊. , Comma.
: Colon.
; Semi-colon.
‘ Apostrophe or single quote. ” Double quote
_ Underscore.
() Brackets, also called round brackets or parentheses. [] Square brackets.
{} Curly brackets.
<> Angle brackets.
~ Tilde or twiddle.
& Ampersand or and sign. | Pipe or vertical line
As a shortcut, MATLAB allows you to pass only one parameter if you want to create square matrices. For example:
creates a 4 × 4 square matrix of zeros.
Two other useful functions for creating matrices are
􏺐 eye. This creates an identity matrix. This will always be a square matrix, so you only pass in one parameter. For example eye(5) creates the 5 × 5 matrix. Notice that the name of this function is a pun. The word eye is pronounced the same as the letter I.
􏺐 diag. This creates a diagonal matrix. E.g. diag([2 4 7]) creates a 3 × 3 diagonal matrix with the numbers 2, 4 and 7 on the diagonal. Note that diag takes a vector parameter.
Creating evenly spaced vectors is also a very common task. One way to do this is to use the special colon operator :.
zeros (4)

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 7
To create a horizontal vector containing all the whole numbers between 1 and 100 one enters:
For the whole numbers between 20 and 50 one enters:
You can also specify the step size. For example, for the numbers between 20 and 50 going up in steps of 3 type
The general syntax is
Note that the above box doesn’t contain real code, you are meant to replace the text in angle brackets with your choice of variables and numbers. We’ll use this notation without comment from now on.
One other way to create evenly spaced vectors is to use the function linspace. For example linspace(30,70,10) creates a vector containing 10 elements evenly spaced between 30 and 70. Whether you use the colon operator or linspace simply depends on whether you want to specify the number of steps or the step size.
1.3.3 Dot operators
Suppose that dollarPrices contains the stock price (in dollars) for the ACME corporation for every day in the last week and that r contains the USD to GBP exchange rate for every day in the last week:
then to compute the stock price for ACME in GBP for every day in the last week, we want to multiply together the vectors s and r cell by cell. We do this using the operator .*. That is a star with a dot in front.
1:100
20:50
20:3:50
::
dollarPrices = [ 100 105 103 102 103 ] gbpToUsdRates = [ 0.61 0.62 0.63 0.62 0.61]
gbpPrices = dollarPrices .* gbpToUsdRates

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 8
So .* multiplies vectors in a very di􏺈erent (and simpler) way than standard matrix multiplication. In particular you can use .* to multiply an m × n matrix with another m × n matrix whereas you can use .* to multiply a m × a matrix with an a × n matrix.
There are dotted versions of the operators ^\lstinline and / too for when you want to raise every cell of a matrix to a given power or when you want to divide matrices cell by cell. There is no need for dotted versions of + and − because + and − already add and subtract cell by cell.
It is always easy to work out if you want to use a dot operator or a standard matrix operator 􏺌 apart from anything else you will usually get an error caused by the matrices being the wrong size if you attempt to use the wrong type of operator. Generally speaking you use normal matrix multiplication if you are thinking of your matrices as linear transformations and your vectors as points in a vector space. If, as in the stock example above, the vectors just contain data without any geometric interpretation, you will usually use dot operators.
Notice that functions such as exp and sin work on matrices, but they behave like the dotted operators. In otherwords they perform exp and sin component- wise. This is standard in MATLAB, whenever it makes sense, functions can take matrices as arguments and they perform their standard operation component by component.
Tip: Choosing variable names
At the start of this tutorial we used short variable names like a and b. We’ve now started using longer names like gbpToUsdRates.
Variable names in MATLAB should not contain spaces and should not begin with numbers but otherwise they can be a mix of numbers and letters. MATLAB is case sensitive, so the variables a and A are di􏺈erent. The fact that you can’t use spaces isn’t much of a problem, just use camel case (starting new words with a capital letter). Its called camel case because the words have humps like camels.
In mathematics it is conventional to use single letter variable names 􏺌 to the extent that mathematicians borrow letters from Greek and Hebrew to make their formulae shorter. In computing longer names are preferred. The big advantage of longer names is that it is much easier to understand what is going on when you look at code with long variable names. The code: gbpToUsdRates = dollar- Prices .* gbpToUsdRates is pretty self explanatory. I strongly recommend using long variable names.
1.3.4 Statistical functions
When you think of a matrix as being a matrix of data rather than a linear transformation, there are various statistical functions you might want to apply to the matrix: sum, mean, std, median, prctile all work in a similar way. For

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 9
example sum(v) computes the sum of the elements in a vector or the sum of the columns of a matrix.
The function std computes the standard deviation of a vector. By default it computes the sample standard deviation, but you can get it to compute the population standard devation if you want – see the online help.
The function prctile computes a given percentile of a vector of data.
Another very useful function is size which tells you the dimensions of the vector or array and length which tells you the largest dimension.
The function hist plots a histogram of a vector of data. For example, recall that the function randn generates normally distributed random numbers. So the following code will plot a histogram of a random sample of ten thousand numbers from the normal distribution:
There are two things you probably won’t like about this – 􏺉rstly the his- togram doesn’t contain very many bars so it doesn’t look as normally distributed as you might like and secondly it isn’t very helpful to print out the array of ten thousand numbers. Here is how you 􏺉x those issues:
We have added a semi-colon on the end of the 􏺉rst line. It means 􏺆don’t print the result􏺊.
On the second line we have passed in an extra parameter of 100, this is the number of bars to show in the histogram.
1.4 Putting it all together
We can combine all of these ideas to perform some quite sophisticated calcula- tions.
Example 1: Use MATLAB to compute the sum
1+2+22 +23 +24 +…+210
Solution: We 􏺉rst create a vector of the numbers 0 through 10. We then use the .^ operator to compute the associated powers of 2 and store the result in powers. We then compute the sum.
sample = randn (10000 , 1) hist( sample )
sample = randn (10000 , 1); hist( sample , 100 )

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 10
You could do this all in one line if you wanted: sum( 2.^(0:10) ) but it is usually easier to understand code that has been broken into small pieces.
Example 2: A robot walks a distance X1 east, a distance X2 south and then climbs a distance X3 up. The Xi are independent and normally distributed with mean 1. Negative distances should be interpreted in the obvious way. Using a MATLAB simulation, plot an approximate histogram of the total distance travelled.
Solution: We create a sample of 1000 possibilities.
x = 0:10; powers = 2.^x; sum( powers )
X1 =
X2 =
X3 =
distance = sqrt( X1.^2 + X2.^2 + X3.^2 ); hist( distance , 20 );
randn (1000 ,1); randn (1000 ,1); randn (1000 ,1);
1.5 Exercises
Use MATLAB to answer the following questions:
􏰒1 􏰓4 1) What is √2(1+i) ?
2) What is the 95-th percentile of the normal distribution (with mean 0 and standard deviation 1).
3) How would you create a vector containing the 􏺉rst 50 odd integers in MAT- LAB? What is the sum of the 􏺉rst 50 odd integers?
4) How would you create a vector of the cubes of the 􏺉rst 50 odd integers in MATLAB?
5) What is the sum of the cubes of the 􏺉rst 50 odd integers?

CHAPTER 1. PERFORMING CALCULATIONS IN MATLAB 11
6) Use the matrix inverse function inv to solve the equations:
x1+2×2+3×3 = 5 −2×1+3×2+4×3 = 6 1×1+3×2+2×3 = 7
Solve the same equations using the \ and / operators. MATLAB will use Gaus- sian elimination if you use the division operators, but will compute the matrix inverse if you use inv. These are two quite di􏺈erent algorithms for solving linear equations. Which is more e􏺍cient?
7) Recall that π = 4(1− 1 + 1 − 1 +…). Compute π to three decimal places. 357
8) Create a sample of ten thousand numbers selected from a normal distribution with mean 10 and standard deviation 20. Plot a histogram to make sure it looks right. Also check your answer using the mean and std functions.
9) Use the documentation to 􏺉nd out how to use the function randi. Suppose that 100 dice are thrown and the numbers on the dice are added. Use randi to simulate throwing all 100 dice 10000 times and plot a histogram of the sum. What do you expect the histogram should look like and why?
1.6 Summary
We have learned how to use MATLAB as a sophisticated calculator.
We have learned how to store intermediate steps of a calculation in variables. We have learned how to create matrices by entering them in full or by using
the functions zeros, ones, eye, randn and diag.
We have learned how to perform operations on matrices. We can perform
standard matrix operations such as multiplication with *. We can perform elementwise operations with operators such as .*.
We have learned how to compute statistics for a vector of data using func- tions such as std, mean, sum, length and hist.