Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Maltlab Practicals Mathematics Methods, Exercises of Mathematics

Introduction to Matlab,Variables,Script M-Files and Graphing,Arrays and Polynomial Functions and Symbolic Toolbox From University of South Australia.

Typology: Exercises

2021/2022

Uploaded on 02/11/2022

rajeshi
rajeshi 🇺🇸

4.1

(9)

237 documents

1 / 60

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MATHEMATICAL METHODS FOR ENGINEERS 1 (MATH 1063)
CALCULUS 1 (MATH 1054)
MATLAB Practicals
Kuva Jacobs and Yuliya Tugai
School of Information Technology & Mathematical Sciences
University of South Australia
February 2008, February 2013 (revised)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c

Partial preview of the text

Download Maltlab Practicals Mathematics Methods and more Exercises Mathematics in PDF only on Docsity!

MATHEMATICAL METHODS FOR ENGINEERS 1 (MATH 1063)

CALCULUS 1 (MATH 1054)

MATLAB Practicals

Kuva Jacobs and Yuliya Tugai

School of Information Technology & Mathematical Sciences

University of South Australia

February 2008, February 2013 (revised)

ii

MME 1 & Calculus 1 – MATLAB Practical 1

Practical 1: Introduction to MATLAB

Aim of this Practical

  1. Get a general understanding of the purpose of MATLAB.
  2. Understand the MATLAB Workspace a) start up MATLAB b) type commands in main window c) change current directory
  3. Use MATLAB as a calculator a) perform some arithmetic calculations b) understand the importance of operators, and functions c) use MATLAB’s help files d) use functions like sin x ,cos x , or | x | to solve problems

Working Through This Practical

  • Go through this practical at your own pace. It explains the environment in more detail than the following practicals.
  • Do each exercise or activity in the shaded areas.
  • Ask your practical supervisor if you have any questions or need advice.
  • MATLAB code will always be denoted by the courier font.
  • If you don’t finish during the scheduled practical time, it is your responsibility to finish it before your practical next week.
  • An arrow > at the start of the line in an exercise indicates an activity for you to complete.

What is MATLAB? MATLAB is a powerful mathematical software package used by both engineers and mathematicians in the workplace. The name stands for MATrix LABoratory. Originally designed for manipulating matrices, MATLAB is great for many different mathematical tasks.

Why do I have to learn MATLAB? Some good reasons for learning MATLAB include

  • It will allow you to check your assignment/homework calculations
  • You will gain a better insight into mathematical functions through complex graphing that can’t easily be done by hand
  • You can quickly find solutions to problems that take a long time by hand (like finding the determinant of a 5x5 matrix)
  • Later, you will be able to find approximate numerical solutions to problems that can’t be solved by hand (like complicated integrals)

Getting Started in MATLAB Availability : MATLAB is available in the following PC Labs at Mawson Lakes : A2-23, GP1-06, F1-13, F1-15, F1-17, P1-12, P1-13, P1-15, MLAV, MLAV03. It is not available in the barns. For further availability check http://w3.unisa.edu.au/ists/students/pools/default.asp under software and hardware search. You will need to type MATLAB in Software search box. You can also check the current PC availability under find a computer available for use.

MME 1 & Calculus 1 – MATLAB Practical 1

To understand better the purpose of the three windows, type in the simple command 3+5 in the Command Window and press enter. What happened in the Command, Command History and Workspace Windows?

MATLAB as a Calculator MATLAB can be used as a powerful calculator. The following exercises demonstrate the order in which MATLAB evaluates expressions.

Exercise: Calculations in MATLAB The following commands illustrate the order of priority when evaluating expressions.

Before typing each command into your Command Window , think about what you expect the answer to be. If the output differs from your expected answer, figure out why. Type in the following commands, pressing E nter after each one. 52+ 3+5 What if instead, we want to add 3 to 5 and then multiply the result by 2? We can use brackets to change the order of evaluation as MATLAB will evaluate the contents of each bracket pair first. Type in the following line of code: (3+5)* Coding tip: Many students have troubles matching bracket pairs. Experienced MATLAB users reduce these errors by

_1. typing both brackets ( ),

  1. then using the back arrow key ← to move back and fill in the bracket contents (3+5)._

The following code is not valid. Type it in, press Enter, then read the error message and change the code so that it works (note the vertical line pointing to the first error). 2(3-5) Coding Tip: The up-arrow key ↑ on the keyboard will recall a previous line for you to edit. Type in the following lines to figure out what the hat ^ key represents. 3^ 3^ Figure out the answers you would expect for the following two lines of code and then type them in to verify your answer. 9-3^ 81/3^

As we have just seen, the simplest mathematical operators are represented by the following symbols.

Symbol Operator Order of Priority ^ (^) Raise to a power 1 evaluated first

  • Multiplication 2 / (^) Division 2 evaluated after any powers
  • (^) Addition 3
  • Subtraction 3

evaluated after any powers, multiplication and division.

MME 1 & Calculus 1 – MATLAB Practical 1

Order of Evaluation

Operator Order of Priority

  • The power operator has the highest order of priority.
  • Multiplication and division both have equal 2nd^ order of priority.
  • Addition and subtraction both have equal 3rd^ order of priority. ‘Left-to-right’ rule Expressions are evaluated from left to right: the leftmost operation is performed first and the rightmost operation is performed last. However, note that the operator order of priority supersedes the above left-to-right rule.

Brackets Round brackets, ( ), can be used to change the order of operations: any expression enclosed in brackets will be calculated first

Exercise: Exploring the Effect of Brackets

Type the following arithmetic expressions in the Command Window. Mentally calculate the answers before pressing the Enter key. (8+6)/(10-2^3) 8+6/(10-2^3) 8+6/10-2^ Coding Tip: The up-arrow on the keyboard will recall a previous line for you to edit.

Exercise: Minimising Required Brackets The following expressions both have a value of 12.

Type in the equivalent MATLAB expressions to obtain the correct answer using as few pairs of brackets as possible.

(needs 1 pair of brackets)

3 / 2

(needs 3 or 4 pairs of brackets)

MME 1 & Calculus 1 – MATLAB Practical 1

MATLAB/Coding Terms you should become familiar with Command, Command Window, Command History, Workspace, Current Directory/Folder, Evaluate, Line of Code, Operator, Operation, Order of Evaluation, Order of Priority, Elementary Mathematical Functions, Expression To Hand Up: Solutions for Kiwi Exercise

MME 1 & Calculus 1 – MATLAB Practical 2

Practical 2: Variables, Script M-files and Graphing

Aims of Practical

  1. Understand the purpose of variables and how to create variables.
  2. Write a script M-File (a list of MATLAB commands, saved in a file) with an emphasis on using appropriate comments.
  3. Learn how to plot a graph. a) Plot a graph of a straight line with fixed start and end points. b) Plot a graph of a straight line with variable start and end points. c) Plot a graph with two lines. d) Use key plotting options including setting the title and axis.

Naming of Numerical Values in MATLAB Why would we want to name numerical values? Here is one example: Consider the polynomial function yx^2  4 x  3 to be calculated for x = 3. We could do so by

typing in the following: 3^2 + 4*3 + 3 but what if we also want to know the answer when x = 7 and x = 5? Wouldn’t it be easier to create a name for 3 called x as follows: x = 3 and then evaluate our polynomial function by typing in: x^2 + 4x + 3 x is what we call a variable.

Exercise: Using Variables

Type in the above lines to set the value of x equal to 3 and then evaluate the value of the polynomial y. Warning: The above code contains an error that is commonly made by learners. What is the error? Change the value of x to evaluate the polynomial for x = 5 and 7. You will need to re-run the command to solve the polynomial each time you update x. Coding Reminder: The up-arrow on the keyboard will recall a previous line for you to edit.

Variables Variables must be assigned values in the following format before they can be used in an expression. = Tip: Angular brackets <> will be used to represent something generic that will be replaced in a specific example.

What this statement means is that the left hand side of an equals sign is always a variable name, say, x. The right hand side is an expression representing a new value to be assigned to that variable.

MME 1 & Calculus 1 – MATLAB Practical 2

Naming Variables It is a good programming practice to give your variables meaningful names, so that you and other people can read your code easily.

Exercise A love-struck engineer specialising in planning the foundations of a building wrote the following code to calculate the area of a rectangle.

Determine what each variable represents and then rename the variables to write the new code in MATLAB with meaningful variable names. dinner = 4 nice = 7 roses = dinner*nice

Some important rules for variable names are:

  1. They are case sensitive : nice, NICE,NiCe and NicE are all different.
  2. They can have a length of up to 31 characters Pachycephalosaurus is a valid variable name (although it is quite frustrating to type).
  3. They must start with a letter , followed by any combination of letters, numbers and underscores. For example, week1, week1_prac, MATLAB_prac_1_is_fun,x are all valid variable names.
  4. There are some reserved words that can’t be used as a variable name, i.e. help, pi, sin, pretty, etc.
  5. clear statements are used to delete the values of previous variables. clear all deletes all values, whereas clear just deletes the variable you nominate. It is a good programming practice to start your code with command clear all.

My preferred naming convention is to capitalise the start of each new word, as in thisIsALongVariable however some people prefer to separate words with underscores, as in this_is_a_long_variable.

Exercise

Use MATLAB to evaluate the following functions at the given values of x. Type in the command clear x beforehand.

f  3 x  6 , x  5 (answer is 3)

 , x  3 , x  3 x

x g (answers are 1,-1)

h  2 x^2  x , x  2 (answer is 6)

MME 1 & Calculus 1 – MATLAB Practical 2

Comments in MATLAB When we write a code, it is helpful to add comments to describe or explain the purpose of one or more lines of code. Conveniently, the symbol % lets us add text that will be read only by users, not by MATLAB. All characters, letters and words after a percent (%) sign on a given line are ignored, and not executed.

Exercise

Type in the following line (including the comment): t = 9 % sets time variable equal to 9 Then add a comment to the next line, which finds the acceleration at time t. a = 15*sqrt(t) %

Comments as good coding practice Soon, the code you will be able to write will become much more complicated. You will need to add comments to make it easier for both you and others to read.

Script M-files A script M-file allows you to place MATLAB commands in a simple text file and then tell MATLAB to open the file and execute all commands precisely as if you had typed them at the Command Window prompt. Script M-files must have file names ending with extension ‘.m’ and must contain only valid MATLAB code.

Exercise

Open a new script M-file by clicking on New Script while in Home tab. A new window will be opened. It has three tabs: Editor , Publish and View. To create, save, run, and edit your M-file you need to stay in the Editor tab. From now on every M-file should start with comment headers that include your name and student ID as well as a description of the purpose of the code as follows: % Practical 2 Graphing exercise % <Add your name, student ID and today’s date here> Add in the commands: clear all x=2^

Save your M-file, for example, as prac2e1.m in your preferred directory and make sure that the Current Folder in MATLAB is set to the same location. Enter command prac2e1 (or whatever name you saved your M-file as) in the Command Window. It should execute your M-file code. Please, note absence of the file extension .m

Coding Tip: When you create M-files, try typing only the first couple of lines of code and check that the M-file works.

MME 1 & Calculus 1 – MATLAB Practical 2

Table of the most useful commands for plotting graphs.

hold on

Allows plotting several graphs on the same figure. All commands after this one apply to a current figure, until the hold off command is used. plot([x1 x2], [y1 y2]) (^) plots the straight line between points ( x 1 , y 1 ) and ( x 2 , y 2 ) axis([minX maxX minY maxY]) (^) specifies axis limits legend(‘y1=equation1’, ‘y2=equation2’)

sets the labels for the legend (must be after plot command) xlabel(‘label for x axis’) (^) sets the label for the x - axis ylabel(‘label for y axis’) (^) sets the label for the y - axis

title(‘graph title’) (^) sets the label for the title

hold off

Following commands no longer apply to the current figure.

Exercise:

Modify your script M-file, plotMe to specify an appropriate axis, legend, labels and title. Remember to use the hold on and hold off commands. Use the help files for the plot command to change the colour of the lines.

Important: From now on, it is expected that every graph you make will have an appropriate title and label for both axes.

MATLAB/Coding Terms you should become familiar with Variable, Script M-file, Comment, Valid.

To Hand Up Your commented plotMe.m script M-file with the accompanying appropriately labelled graph.

MME 1 & Calculus 1- MATLAB Practical 3

Practical 3: Arrays

Aim of this Practical

  1. Learn how to create an array, a list of ordered numbers. a) understand the advantages of the different ways of creating arrays including the standard format and the linspace command. b) access specific numbers in arrays using their position. c) use array commands to find quantities such as the sum of the numbers in the array.
  2. Learn how to plot a graph using arrays and the plot command.
  3. One-dimensional array operations.
  4. Use the cell environment to execute several lines of code in an M-file.

Arrays An array in MATLAB is a list of objects, e.g. numbers or characters that can easily be stored and accessed. Each object or element in the array has a fixed position.

Arrays are useful in MATLAB as they allow an operation to be performed on more than one number using a single command. Arrays are also important for plotting.

Exercise: Creating Arrays

Try these different ways of creating arrays.

  1. Type in the elements of the array one-by-one at the prompt within square brackets. Elements should be separated by commas or spaces. x1=[2, 5, 13, -1, 0.111, pi] advantage : easy for small set of numbers, disadvantage : tedious and time consuming for lots of numbers.

  2. Create an array of integers with increment 1 (by default) from smallest to largest: smallest= -3; largest= 24; x2= [smallest:largest] The following is also valid: x2= [-3:24] advantage : fast, especially for many numbers, disadvantage : increment of 1 only.

  3. You can also specify the increment or the step size, h. Check the following (note you must define smallest and largest first). h= 0. x3= [smallest:h:largest] advantage: allows different increments, disadvantage: one must calculate number of elements.

  4. You can specify the number of points instead of the step size using the linspace command. points= 20; x4= linspace(smallest,largest,points)

MME 1 & Calculus 1- MATLAB Practical 3

Exercise: Using the Array Functions

Create a script M-file called arrayFunctions.m to run the following code, starting by entering comment headers with your name, the date and the purpose of the M-file.

  1. Create an array of 23 random numbers between 0 and 200 called randy using the following command:

randy = 200*rand(1,23)

  1. Find the average of the numbers in randy using the sum and length commands.
  2. Find the largest element and the smallest element in randy and swap them.
  3. Sort randy into ascending order. Do you know how to sort it in descending order?
  4. Find the indices of elements in randy which are larger than 100.

Plotting Graphs with Arrays Last week we introduced some of the basic plotting functionality, including plotting a straight line and modifying the graph axes, title etc. This week we will look at using arrays to plot functions. How does the plot command work? Actually, it draws a straight line segment between each set of coordinates that you give it. If the line you are trying to draw is a curve, it will appear smooth by plotting many tiny lines.

Exercise: Graphing with Arrays

Create a script M-file called plotArray.m for the following code in order to plot a sine curve between 0 and 2 . Don’t forget to add comment headers. clear all points = 3 x = linspace(0,2*pi,points) y = sin(x) plot(x,y) What is wrong with this graph? Change the variable called points to 5 and save before re-running the code, then increase it to 10, 20, 40, 80, 200. Examine each new graph and stop when you think that it is acceptable.

The MATLAB Variable Editor Switch to ‘VARIABLE’ tab to edit your variables/arrays manually. It allows you to edit your arrays and variables in a spreadsheet environment.

Press Open icon to choose a variable or an array. Otherwise simply double click on the name of the variable or an array you wish to edit in your Workspace Window. A new window named ‘Variables - ’ will be opened. Change any value and see what happens in the Workspace Window and in the Command Window which moved below the new window. Choose any of your existing arrays. Plot a graph by highlighting the cells that you wish to plot and then click on the graph button in Plot tab at the top of the grey coloured area. You can choose from a range of plots by clicking the corresponding icon. To switch off Variable Editor close the window named ‘Variables - ’.

MME 1 & Calculus 1- MATLAB Practical 3

One-dimensional Array Operations

MATLAB has a specific array or ‘element-by-element’ multiplication, • *, designed for one-dimensional arrays, that is also called ‘Hadamard product’ in mathematics, and uses a dot, • , before multiply sign, , eg V1•V

  • or [1 2 3] •* [0 1 1] = [0 2 3] 

Exercise: Multiplication with Arrays

First define A=linspace(0,5,11) and B=linspace(1,6,11), c=4, and d=- Find out what happens if you run the following equations: Ac+d Ac+dB What happens if you multiply? AB

Note: MATLAB sends you an error message that ‘Matrix dimensions should agree’. It means that you forgot to use a dot before the multiplication sign. Matrix multiplication MATLAB referred to will be taught in further courses.

Try it again with a dot to perform array multiplication: A. *B. .

Exercise: Multiplication of Arrays and Scalars

Type in the following commands to find out which one works. A5 A.5 5*A A/5 5/A 5./A A^2 2^A 2.^A

Table of Array Multiplication Expressions Involving a Dot Before Operator

A.*B (^) multiplies corresponding elements of A and B

A./B (^) divides corresponding elements of A and B 5./A (^) divides 5 by each element of A A.^B (^) calculates A(i)^B(i) for every corresponding element in A and B

2.^A (^) finds 2^A(i) for every element of A A.^3 (^) cubes each element in A