20
1 Introduction to MATLAB (Revised October 13, 2016) Contents Opening a MATLAB session ........................................................................................................................................... 2 First MATLAB script........................................................................................................................................................ 3 Comments: ................................................................................................................................................................ 3 Clear command:......................................................................................................................................................... 3 Variables: ................................................................................................................................................................... 3 Operators: .................................................................................................................................................................. 4 Exercise set A: Manipulating variables .......................................................................................................................... 5 for..loop ............................................................................................................................................................................. 6 Exercise Set B: for..loop ......................................................................................................................................... 7 Arrays ................................................................................................................................................................................ 9 Exercise Set C Arrays.................................................................................................................................................... 11 Numerical Analysis.......................................................................................................................................................... 13 Plotting data .................................................................................................................................................................... 14 Exercise Set D: ............................................................................................................................................................. 16 Exercise Set E: .............................................................................................................................................................. 16 Comparing experimental and simulated data ............................................................................................................... 17 Exercise Set F: ............................................................................................................................................................. 17 Appendix ......................................................................................................................................................................... 18 How to deal with errors ............................................................................................................................................... 18 Before putting your hand up ................................................................................................................................ 18

Introduction to MATLAB Contents

  • Upload
    hanga

  • View
    232

  • Download
    4

Embed Size (px)

Citation preview

Page 1: Introduction to MATLAB Contents

1

Introduction to MATLAB (Revised October 13, 2016)

Contents Opening a MATLAB session ........................................................................................................................................... 2

First MATLAB script........................................................................................................................................................ 3

Comments: ................................................................................................................................................................ 3

Clear command: ......................................................................................................................................................... 3

Variables: ................................................................................................................................................................... 3

Operators: .................................................................................................................................................................. 4

Exercise set A: Manipulating variables .......................................................................................................................... 5

for..loop ............................................................................................................................................................................. 6

Exercise Set B: for..loop ......................................................................................................................................... 7

Arrays ................................................................................................................................................................................ 9

Exercise Set C Arrays .................................................................................................................................................... 11

Numerical Analysis .......................................................................................................................................................... 13

Plotting data .................................................................................................................................................................... 14

Exercise Set D: ............................................................................................................................................................. 16

Exercise Set E: .............................................................................................................................................................. 16

Comparing experimental and simulated data ............................................................................................................... 17

Exercise Set F: ............................................................................................................................................................. 17

Appendix ......................................................................................................................................................................... 18

How to deal with errors ............................................................................................................................................... 18

Before putting your hand up ................................................................................................................................ 18

Page 2: Introduction to MATLAB Contents

2

Introduction

MATLAB is a technical computing language that is primarily used to solve mathematical problems. Instructions or code used by MATLAB are written using strict rules. The following is intended as an introduction to writing and debugging some of the rules used by MATLAB. Opening a MATLAB session The first step is to start MATLAB, open blank editor session and dock the editor session to MATLAB.

To open a blank script, press

To dock the script session press

MATLAB may open with an undocked blank script

Page 3: Introduction to MATLAB Contents

3

First MATLAB script In this section the student will be shown how to create their first MATLAB executable script or M-file. The student will be introduced to comments, commands, variables and operators. Type in the following code into the script session opened previously, pressing enter at the end of each line:

Comments: Text typed after a % turns green automatically denoting comments. Comments help the programmer remember what the code means and are not executed. Clear command: The first line is the clear command which erases the MATLAB work space. Place it at the beginning of each script.

Variables: a, b and c are examples of variables and they represent “storage” sites in the computer’s memory. The equal sign places the value on the right into a variable’s storage site. For example: a = 1 places the value 1 into the storage site called a. This is also called initializing the variables. These variables are then manipulated by the computer.

Important: Do not use spaces when creating a variable name!!

Page 4: Introduction to MATLAB Contents

4

Operators: Operators are used to perform actions on the contents of the variables. For example, the script:

c = a + b; uses the operator “ + ”to add the contents of the variables a and b together and the “ = ” operator places the answer into the storage site called c. Other operators used by MATLAB include multiplication * , subtraction –, division / and the exponent ^. It is important that the variables on the right hand side of a MATLAB equation be initialized or else MATLAB will give an error. After typing in the MATLAB code press F5 to execute it. You will be asked to save the file, call it first. After executing the script, MATLAB should look something like this:

Note: When naming a file do not use spaces

Contents of the variables a,b and c

Answer Command Window

Page 5: Introduction to MATLAB Contents

5

Exercise set A: Manipulating variables 1. Write a script which multiplies 2 and 3 and gives the answer.

a. Open a new blank script and type clear; on the first line. b. Create two memory locations called a = 2; and b = 3; on separate lines. This also

initializes the memory locations. Do not forget the semi-colons. c. Include on a new line that c = a*b without semi colon. d. Press F5, save the script as A1 e. See command window for answer

2. Write a script that divides the contents of one memory location by another. Open a new blank script and type the command clear; on the first line. Create two memory locations called a = 1 and b = 3. On a new line place the value of a/b into the variable c, without semi colon. Save the script as A2

3. Write a script that adds one to a memory location called a. Open a new blank script and type in the following:

save the file as A3; what is the variable a equal to? (answer a = 4) 4. Write a script that adds the values from two memory locations: t and d. Store the resulting value

into memory location called t. Open a new blank script and type in the following:

save the file as A4. What is variable t equal to? (answer t = 3.1)

5. Write a script that solves for the factorials of: 1,2,3,4 and 5. (For example, the factorial of 4 is 1*2*3*4). Use only one variable, z. Type clear; on the first line and give z the initial value of one (z = 1). Second line, z = z*2 no semi colon, etc. Requires 6 lines of code. Save script as A5.

clear; %initialize variables t = 3; dt = 0.1; %computation t = t+dt; %answer t

clear; %initialize variables a = 3; %computation a = a+1; %answer a

Page 6: Introduction to MATLAB Contents

6

for..loop It is often necessary to repeat the same calculation a number of times. The for..loop is one example of how one can do this in one step. Start a new blank script editor and type in the following script. The script asks the computer to add 2 to the variable a, 3 times in a row:

Press F5 and save it as count. The variable i is called the loop counter. It starts at one and is incremented by one each time the process in-between the line for i = 1:k and end is performed, until i reaches the value k. What is happening? This:

You can also see what is happening in the loop by scrolling up command window to see the output of count.

clear; a = 0; %initialize variables k = 3; for i = 1:k %loop begins

a = a+2 %adds two to a, k times i %loop counter value

end %loop ends a %result

(A) Initial values are: a = 0; k = 3; (B) Enter loop. What happens is:

First i=1, perform operations within loop a = a + 2, show the value of i

Then i=2, perform operations within loop

a = a + 2, show the value of i Then i=3, perform operations within loop

a = a + 2, show the value of i Then exit loop as i has reached its maximum value, k (which is equal to 3)

Page 7: Introduction to MATLAB Contents

7

Exercise Set B: for..loop 1) Starting with the script named “count”:

Modify the script to add da to the variable a ten times in a row. Set da = 0.1 and do not show the value of i inside the loop. Name it B1

2) Starting with the script named “A4”:

Modifying the following script using a for loop to repeatedly add dt to the variable t ten times. Set dt = 0.1 and do not show the value of i inside the loop. Name it B2.

3) Starting with the factorial script:

Modify it to use the for loop to calculate the factorial of the numbers from 1 to 10. ( Hint: Try the line z=z*i inside the loop) Name it B3.

clear; a = 0; %initialize variables k = 3; for i = 1:k %loop begins

a = a+2 %adds two to a, k times i %loop counter value

end %loop ends a %result

clear; %initialize variables t = 3; dt = 0.1; %computation t = t+dt; %answer t

clear; %initialize variables z = 1; %computation z = z*2; z = z*3; z = z*4; z = z*5; %answer z

Page 8: Introduction to MATLAB Contents

8

4) Start a new blank script and write the following script and save it as B4 and run it.

The position yf at time t is repeatedly calculated 7 times, as ndp = 7. Using output found in the Command Window write down the values of yf and t. Answer: t = 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 y = 18.775, 25.100, 28.975, 30.400, 29.375, 25.900, 19.975

clear; %initialize variables yi = 10; v = 20; a = -9.8; t = 0; ndp = 7; dt = 0.5; %computation for i = 1:ndp t =t+dt yf = yi + v*t + (a*t^2)/2 end %answer

Page 9: Introduction to MATLAB Contents

9

Arrays The program B4 was not a very useful since calculated values have to be written down to be plotted. However, within the MATLAB language there are objects called arrays which can be used to store data. In this section the concept of arrays will be introduced as well as how to use arrays to store and plot data. First, start a new blank script editor and type in the following script:

Second, press F5 and save as exarray1. What is this script doing? First, an array called x of size 5 x 1 is created and filled with zeros using the function zeros(5,1). Second, an arbitrary number is placed in each of the array’s “storage sites”. Third, the value stored within each array location is sent to the Command Window. Examine the Command and Workspace Windows to see how MATLAB stores the data. See appendix at the end of this document for more information about arrays.

clear; % initialize variables x = zeros(5,1); % computations x(1) = 12; x(2) = 27; x(3) = 67; x(4) = 99; x(5) = 21; % answer x

Page 10: Introduction to MATLAB Contents

10

Another array example: Start a new blank script editor, type in the following script:

press F5 save as exarray2 : What is this script doing? First, an array called x of size (n x 1) is created using the function zeros(n,1). Second, the for..loop operation is then used to enter the value of the loop counter, i + 3, into a “storage sites” called x(i) . Third, the values stored within each array location are sent to the command window. Examine the Command and Workspace Windows to see how MATLAB stores the data

clear; %initialize variables

n = 5; x = zeros(n,1); %computations for i = 1:n x(i) = i+3; end %answer x

Page 11: Introduction to MATLAB Contents

11

Exercise Set C Arrays 1. Starting with the script named “exarray2”:

Modify it so that, instead of x(i) = i+3 place the value of the loop counter i squared into x(i). (Answer: The numbers 1,4,9,16,25 will appear in the Command Window)

2. Starting with script named “exarray2”:

Increase the size of the array x to n = 10, create a new variable dx = 0.5, initialize x(1) = 1, the loop counter i should start at 2 and set x(i) = x(i-1) + dx. Show x. (Answer: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5)

3. Start a new blank script editor and write a short script which (a) Uses the function zeros(n,1) to create an array called t of size n=5. (b) Initializes a variable dt = 0.1. and set t(1)=0; (c) Using the for..loop place within each array location t(i) = t(i-1)+dt; (d) Start the for..loop counter at i = 2. (e) Press F5 and name the file timeex2. The output should be:

clear; %initialize variables

n = 5; x = zeros(n,1); %computations for i = 1:n x(i) = i+3; end %answer x

clear; %initialize

variables n = 5; x = zeros(n,1); %computations for i = 1:n x(i) = i+3; end %answer x

t = 0 0.1000 0.2000 0.3000 0.4000

Page 12: Introduction to MATLAB Contents

12

4. Modify the script timeex2 (a) Create a new array called x of size (n,1) (b) A new variable v = 12 (c) Initialize x(1) = 0.5 (d) Add the line x(i) = x(i-1) + v*dt (e) what are x and t

x = 0.5 1.7 2.9 4.1 5.3

t = 0.0 0.1 0.2 0.3 0.4

Page 13: Introduction to MATLAB Contents

13

Numerical Analysis Start a new script and type in the following:

The variables position yf, velocity vf and time t are repeatedly calculated ndp times. Determine yf for tt = 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5. Save the script as projectile. Notice that both the outputs of projectile and B4 give the same answer at t = 0.5. This script uses a technique called numerical analysis to solve the projectile problem. Briefly, numerical analysis involves dividing the range of one or more of the variables into small intervals and solving for a given variable while assuming two things. First, the other variables are constant during that interval. Second, the new values are calculated using previous values of the variable. In the above example, time is divided into short intervals of size dt, the velocity and position are then calculated assuming the acceleration is constant during the interval dt. The new t and yf and vf are calculated using the previous t and yi and vi For example t = t + dt. Using numerical techniques to solve

𝑦𝑦 = 𝑦𝑦0 + 𝑣𝑣0𝑡𝑡 +12𝑎𝑎𝑡𝑡2

is more complicated than necessary. However, there exist many problems that cannot be solved using simple equations and numerical techniques are required. We will learn more about numerical techniques later

clear; %initialize variables ndp = 1001; %number of data points tt = 0.5; dt = tt/(ndp-1); t = 0; yi = 10; %initial position vi = 20; %initial velocity a = -9.8; %acceleration %computations for i = 1:ndp %for loop begins t = t+dt; % t is increased by dt yf = yi + vi*dt + (a*dt^2)/2; % calculate final y vf = vi + a*dt; % calculate final velocity yi = yf; % set new initial position yi vi = vf; % set net initial velocity vi %restart loop end %for loop ends %answer t %final y and time yf

Page 14: Introduction to MATLAB Contents

14

Plotting data With the previous script projectile the values for vf at various times t were lost unless you wrote them down. In the following script changes are made to the script “projectile” to include arrays for position, velocity and time. These arrays are then used to plot y as a function of t. Start a new blank script editor and type the following script, save as falling and then press F5.

Because the script is storing the values in an array it is possible to replace the line:

yf = yi + vi*dt+0.5*a*dt^2 with

y(i) = y(i-1)+v(i-1)*dt+0.5*a*dt^2

The value stored in y(i-1) has become the initial value for y in the interval dt which will be used to determine y(i) the final value.

clear; ndp = 351; %number of data points t=zeros(ndp,1); %initialize t, v and y array size v=zeros(ndp,1); % y=zeros(ndp,1); % tt = 3.5; %total time of simulation dt = tt/(ndp-1);%time between data points t(1) = 0; %starting values of t, y and v y(1) = 10; v(1) = 20; a = -9.8; for i = 2:ndp t(i) = t(i-1)+dt; y(i) = y(i-1)+v(i-1)*dt+0.5*a*dt^2; v(i) = v(i-1)+a*dt; end figure(1) %figure name plot(t,y) xlabel('t (s)') ylabel('y (m)') title('Projectile motion without friction')

The loop now starts at 2

Page 15: Introduction to MATLAB Contents

15

The last part of the code plots the displacement y as a function of time. Use the Data Cursor function to view the contents of graphed variables

Contents of a variable may also be viewed by double clicking on the variables name found in the work space window. Velocity as a function of time can be plotted by adding the following script to the end of falling

figure(2) plot(t,v) xlabel('t (s)') ylabel('v (m/s)') title('Vertical velocity as a function of time')

First click on Data Cursor function

Then click on graph to view contents of variable

Page 16: Introduction to MATLAB Contents

16

Exercise Set D: Using the script falling, answer the following questions. The values of the different variables can be found out by using the Data Cursor function.

(i) A projectile is thrown straight up with an initial velocity of v(1) = 20 m/s and initial position y(1) = 10 m.

(a) What is the maximum height reached by the rock? (Answer 30.408m) (b) What is the position and velocity of the projectile after 3 s? (Answer 25.9m, -9.40m/s)

(ii) Set initial velocity to 10 m/s and y(1) = 1000 m

(a) What is the position and velocity of the projectile after 1 s? (Answer: 1005.1m, 0.200m/s)

Exercise Set E: The script falling describes the position of a projectile without friction using y. In reality friction does exist and it is possible to include effects of friction on the trajectory of a projectile.

One possible way to include friction is to have a velocity dependent acceleration given by: africt(i) = -9.8 - b*vfrict(i)/m.

Where africt(i) is the acceleration calculated using: b = 0.2 (the coefficient of friction due to air resistance), m = 1 the mass of the object and vfrict(i) is the object’s velocity at point i.

Using the script falling as a template, write a new script which calculates yfrict, position with friction. Display yfrict vs t using the function plot(t,yfrict). Name the new script fallingwithfriction.

Hints:

• Create a second set of arrays yfrict = zeros(ndp,1), vfrict = zeros(ndp,1)

and africt = zeros(ndp,1).

• Enter the values yfrict(1) = 10; and vfrict(1) = 20;

• The initial velocity-dependent acceleration is africt(1) = -9.8 - b*vfrict(1)/m.

• Inside the loop you must replace the variable a in the calculation of y(i) by africt(i-1).

• You must also add the line africt(i) = -9.8-b*vfrict(i)/m; after the line for

v(i);

Page 17: Introduction to MATLAB Contents

17

Comparing experimental and simulated data

Many times experimental data must be compared with simulations to help develop a better understanding of the underlying physics. To demonstrate this, data collected from the two-dimensional projectile motion experiment will be compared to a simulation.

Exercise Set F: In this exercise the experimental trajectory is the set of points on the large sheet of paper obtained while doing the projectile experiment. Using EXCEL, graph the vertical position as a function of the horizontal position. Using falling as a template, write a program compare that calculates both the x and y components of a projectile under the influence of gravity. The acceleration is given by a = gsin(theta), where theta is the angle of inclination of the air table. Ignore friction and use the same dt as the experiment. You will need the horizontal and vertical components of the initial velocity (first interval) as well as the initial positions in x and y. To output data from MATLAB to Excel first, double click on a variable in the Work Space Window and then select the contents of the variable. Second copy past to Excel the contents. Save the x and y variables calculated in compare to the Excel sheet and compare them with the projectile experiment data.

vx

vy ymax

xmax

v

t = 0, x = 0 and y = 0

Page 18: Introduction to MATLAB Contents

18

Appendix How to deal with errors Before putting your hand up First, read the Command window text. Questions you should ask yourself:

i. Are there any spelling mistakes? a. Variables or functions

ii. Are all the variables initialized? iii. Is there missing any syntax?

a. An example would be missing colon.

Example of spelling error giving Undefined Variable error

Variable spelt wrong gives an error of undefined variable

Page 19: Introduction to MATLAB Contents

19

Missing index i

Page 20: Introduction to MATLAB Contents

20

Pre-lab problem:

A ball is launched from an initial position (xi, yi) with a velocity v and an angle Θ and lands on the ground at (xf, yf). Solve for projectile’s flight time in terms of v, and yi and yf. Then determine xf.

v (xi,yi)

Θ

(xf,yf)