




















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Introduction to Matlab,Variables,Script M-Files and Graphing,Arrays and Polynomial Functions and Symbolic Toolbox From University of South Australia.
Typology: Exercises
1 / 60
This page cannot be seen from the preview
Don't miss anything!
ii
MME 1 & Calculus 1 – MATLAB Practical 1
Practical 1: Introduction to MATLAB
Aim of this Practical
Working Through This Practical
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
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 ( ),
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
evaluated after any powers, multiplication and division.
MME 1 & Calculus 1 – MATLAB Practical 1
Order of Evaluation
Operator Order of Priority
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
Naming of Numerical Values in MATLAB Why would we want to name numerical values? Here is one example: Consider the polynomial function y x^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.
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:
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
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.
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.
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.
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.
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.
randy = 200*rand(1,23)
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
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