13
DE2-EA 2.1: M4DE Dr Connor Myant 2017/2018 MATLAB Problem Sheet Comments and corrections to [email protected] Lecture resources may be found on Blackboard and at http://connormyant.com

Dr Connor Myant 2017/2018 - WordPress.com Connor Myant 2017/2018 MATLAB Problem Sheet ... Ben Collinson - b.collinson@ ... I made countless errors working on the codes for this module

  • Upload
    dokhanh

  • View
    212

  • Download
    0

Embed Size (px)

Citation preview

DE2-EA 2.1: M4DE Dr Connor Myant

2017/2018

MATLAB Problem Sheet

Comments and corrections to [email protected]

Lecture resources may be found on Blackboard and at http://connormyant.com

Contents Introduction to MATLAB Exercises ......................................................................................................... 3

Why do we have to learn MATLAB? ................................................................................................... 3

Getting MATLAB .................................................................................................................................. 3

Help for MATLAB ..................................................................................................................................... 4

Online .................................................................................................................................................. 4

Inbuilt .................................................................................................................................................. 4

Basic MATLAB Window ........................................................................................................................... 4

Basic operations and calculation in MATLAB .......................................................................................... 5

Errors associated with MATLAB .............................................................................................................. 6

M-Files ..................................................................................................................................................... 6

Don’t stress! ............................................................................................................................................ 6

Further Reading ...................................................................................................................................... 7

The Course Work..................................................................................................................................... 7

How to present your work .................................................................................................................. 7

Marking Scheme ................................................................................................................................. 9

Task 1. ................................................................................................................................................... 10

Task 2. ................................................................................................................................................... 10

Task 3. ................................................................................................................................................... 10

Task 4. ................................................................................................................................................... 11

Task 5. ................................................................................................................................................... 12

Task 6. ................................................................................................................................................... 12

Introduction to MATLAB Exercises You have already learnt how to use Python in Computing 1, so you have a good foundational

appreciation of coding. You have used Jupiter as a basic calculator, looping functions and plotting

results. The vision of the following exercises is to help you develop your understanding of the basic

features and some basic functions of MATLAB.

MATLAB looks and feels a lot like Jupiter, and has many of the same capabilities. In general there are

only minor differences in the syntax. MATLAB is a proprietary code commonly used in academic

research and industry. MATLAB is a very powerful software with numerous toolboxes (function

libraries) built in. You can think of MATLAB as a sort of graphing calculator on steroids – it is designed

to help you manipulate very large sets of numbers quickly and with minimal programming.

Operations on numbers can be done efficiently by storing them as matrices. MATLAB is particularly

good at doing matrix operations, in fact its name stands for matrix laboratory. Some of the typical

uses of MATLAB are given below:

• Math and Computation

• Algorithm Development

• Modeling, Simulation and Prototyping

You will be using MATLAB again on your undergraduate degree, in the Big Data and Electronics 2

modules. You may also be asked to use it by your project supervisor for your 3rd and 4th year projects.

If you go onto do post-graduate research you will likely use MATLAB again, this time at a more

advanced level and utilise the numerous, powerful, tool boxes.

There is an open source equivalent to MATLAB called Octave. However, it lacks the toolboxes. So

whilst you have access to MATLAB you might as well use it.

Why do we have to learn MATLAB? Of course you don’t! However, if you want to be a competent design engineer you will find it helpful

to learn MATLAB. MATLAB is widely used for engineering calculations for which a special purpose

computer program has not been written. But it will probably be superseded by something else during

your professional career – very little software survives without major changes for longer than 10

years or so.

Getting MATLAB You should all have MATLAB installed on you DE laptops, if not here are instructions on how to get

and install MATLAB:

1. Go to ICT software shop and register for MATLAB from menu

(https://www.imperial.ac.uk/admin-services/ict/shop/software/more-free-software-

students/)

2. Log in with Imperial details

3. Select and download software

4. Search MATLAB

5. Select home use MATLAB licence

6. Accept agreement

7. Complete order

8. You will receive an e-mail from ICT with instructions on how to download and install

We recommend doing the download and install where you have good internet as files are large.

Install all packages.

Now you can start MATLAB.

Any problems contact ICT DE support, Ben Collinson - [email protected].

Help for MATLAB

Online You have access to the online MATLAB tutorials from MathWorks at:

https://matlabacademy.mathworks.com/

You can work through these step-by-step, or if you prefer you can brush up on topics as you wish.

I strongly recommend you work through the MATLAB Onramp worksheets, particularly those of you

who are a little computerphobic! You don’t need to do all the problems just pick those that are

relevant to your needs, weaknesses or the coursework problems. Working through Onramp chapters

4, 7 and 9 will be particularly useful for this coursework.

There will also be drop in MATLAB surgeries throughout the term which you can attend and receive

help with your code.

There is also a wealth of freely accessible information, chat rooms, and communities online.

There is no excuse for not completing the MATLAB tasks!

Inbuilt To learn more about a certain function, you can use the various help commands. Just type help

command followed by the function you are curious about, e.g.;

help tand

Will explain the function in question inside the command window.

doc tand

Will open the function in a new Help window.

lookfor tand

A great command if you do not know the name of the exact function you want. You can type a key word in and it will search all MATLAB functions that contain that word in their description.

Basic MATLAB Window Once MATLAB opens you should see a similar GUI to the one below. You can alter the setup/location

of the various windows to suit your own preference- they are ‘drag and drop’.

If you want to display extra windows look along the top and click on the ‘Layout’ tab, select the

windows you want from the drop down list.

Basic operations and calculation MATLAB can be employed as a plain old calculator, by simply typing into the command window. You

can write the following into the command window to see what happens;

x=90 y=tand(x) x=pi/2 y=tan(x) format long y format long eng y format short y

MATLAB will display the solution to each step of the calculation just below the command.

We have also assigned a value to the variables x and y, this will be displayed in the Workspace window. It will remain there until you ‘clear’ it. Type the following and see what happens;

clear x x

If you write ‘clear’ and omit the variable everything gets wiped! This is useful when starting a fresh

calculation.

Errors associated with MATLAB You should have noticed an odd answer to;

x=pi/2 y=tan(x)

The answer should be infinite but MATLAB returns a very large number. This is because MATLAB (and

any similar program) stores floating point numbers as sequences of binary digits with a finite length.

Obviously, it is impossible to store the exact value of 𝜋 in this way.

You can minimize errors caused by floating point arithmetic by careful programming, but you can’t

eliminate them altogether. As a user of MATLAB they are mostly out of your control, but you need

to know that they exist, and try to check the accuracy of your computations as carefully as possible.

M-Files Up to now we have been typing into the command window. This is ok for simple tasks and using

MATLAB a basic calculator, but usually we type the list of commands you plan to run into a file. These

are called an M-file, and tells MATLAB to run all the commands together. A benefit from this is the

ability to fix errors easily and re-running the file.

You create an M-File using a text editor and then use them as you would any other MATLAB function

or command. But before using the user defined functions always make sure that the ‘path’ is set to

the current directory.

Select a convenient directory where you will be able to save your files. I advise you to create a folder

specific for this coursework activity to keep all your files in one place.

There are two kinds of M-Files:

• Scripts, which do not accept input arguments or return output arguments.

• Functions, which can accept input and output arguments.

Don’t stress! When you start writing your own scripts and functions in MATALB you will inevitably find that they

don’t work. This can be extremely frustrating and demoralising at times. But, don’t get discouraged,

this is all part of process and just adds to the satisfaction when they do work. If it counts for anything

I made countless errors working on the codes for this module (there are probably a few still in there!).

The more programming you do the better you will become at identifying potential errors, finding faults

and fixing them.

Here are a few things to check as you go through this worksheet;

1. Typos and mistakes – the most common and annoying! Thankfully if MATLAB finds a typo it

usually tells you which line is causing problems (the M-file editor also gives warnings about

potential problems). The hardest ones to find however, are the ones that send the program

into an infinite loop, or weird memory management problems that cause variables to be

assigned incorrect values (e.g. by re-setting a variable inside a loop, or assigning a variable

name you later call as a function). To find these, you need to identify where they occur in the

code – you can use a debugger for this, or run the code line by line, or if you prefer you can

simply add visible steps (messages, pauses, figures) in your code to help identify errors.

2. Miss-understanding the MATLB function – These errors are not hard to find as long as you

take the time to read the function descriptors and use the help files. If you are still struggling

try the function on a simpler task and build up to your requirements.

3. This is a flaw in your understanding or assumptions of the problem – question your results,

plot the trends and check they are right. This isn’t exactly an error in the code but your ego

getting the best of you. Just because you have the number you wanted is it the right one?

4. Unstable or taking too long – These are the hardest issues to fix and often require a whole

new programming strategy to solve the problem you are looking at.

A good practice guide is:

1. Use comments and lots of them! This will help you when coming back to your code later on.

2. Fix typos and just get the code to produce something….anything!

3. Break the code down into sections and check each part/step is producing the right result.

4. Validate your code; try to use your code on something that has already been solved,

something you know the answer to.

5. Check the code’s stability; test your code for different conditions, does it still hold up?

Further Reading These notes are intended as a complete set of notes that should see you through the course work

tasks. However, for the keen beans and those that want the extra help here is some suggested text

books;

Introduction to MATLAB for Engineers, 3rd Edition. William J Palm

MATLAB for Engineers, 5th Edition. Holly Moore

MATLAB: An Introduction with Applications, 5th Edition. Amos Gilat.

The Course Work The following sections describe how to submit your course work, how your work will be marked, and

the task questions themselves.

How to present your work You need to solve the following problems using MATLAB and write your code in a matlab .m file.

Make your MATLAB (.m) file a function, so that when the file is executed, it will solve all the tasks and

display your results at once.

Give the function your name.

Insure you include comments throughout and display your results as requested in each task.

Example:

function [Outputs] = DrConnorMyant (Inputs)

% [] if no output are required, leave empty % () if no inputs are required, leave empty

%% INITIALISE

close all %closes all the opened figures clear %wipes the workspace clc %clears the command window

tic %Please add this. It will time how long it takes your function to run

%% Solution to Task 1. A

Code that will solve the problem

Display answer as either an output in the command window or on a figure….

figure ('name','Task 1') % name each figure after the task number plot (…..) %plot your answer hold on % this allows you to display multiple plots on one graph plot (…..) hold off % it is good practice to turn off the 'hold on' function when you

are finished with the plot grid on axis tight xlabel('V, (\circ)') ylabel('S, C') legend({'X','Y'},'FontAngle','italic','Location','North'); title('Task 1, Question B') set(gcf,'color','w')

%% Solution to next Task

toc %turns off timer

end

Sub functions %stack these at the end of your m file function a = solve(workin, workout) … Code End

If the task asks you to plot something your function will need to create a figure;

All figures should have a white background.

Where appropriate graphs should be displayed with a grid and suitable axis scales.

All graphs should display a legend in a suitable location, and set the font to italic.

All axes should be labelled correctly with units and symbols showing.

All figures must be given a title after the task number (i.e. Task 1, Question B).

You will need to look up how to perform many of these figure stipulations (there are some clues

above!).

If the task asks for a solution, value, vector or matrix to be presented just don’t put a semi-colon (;) at

the end of code line.

Marking Scheme The course work makes up 15% of your M4DE overall grade. And is marked out of 15.

Your submitted file must be named correctly and run when called. Only answers that are displayed

when the function runs will be marked. No editing of the code will be done by the examiners.

One mark is awarded for the first 4 tasks, two marks are awarded for the next 2 tasks, on a pass or fail

basis for each task; i.e. do you display an answer and is the answer correct? (Total = 8)

One mark is awarded for neatness for each task; i.e. is your text clear and concise, is the plot clear and

visible, axes correctly labelled with units etc.? (Total = 6)

The final mark is awarded for the quality of your code (i.e. are your comments clear, did it run

completely error free).

Task 1. Create a vector, V, of 500 equally spaced points between 0 and 720 degrees. Now use V to create two

vectors X and Y that contain the values of the function

𝑆 = 4 sin𝑉 + sin2𝑉

𝐶 = 4 cos𝑉 − cos 4𝑉

Plot your answers in terms of degrees on a graph.

HINT: MATLAB has inbuilt functions such as linspace (Linearly spaced vector) that will help you. You

will also need to check if you are working in radians or degrees when using the trigonometric functions

in MATLAB.

Task 2. Use your knowledge of nested loops and conditional statements (or an alternative method if you

prefer), to construct a 500x500 matrix M(i,j) with;

𝑀(𝑖, 𝑗) = {1 sin(2𝜋𝑖/500) sin(2𝜋𝑗/500) > 0

0 sin(2𝜋𝑖/500) sin(2𝜋𝑗/500) < 0

Display your result as an image using imshow.

OPTIONAL: It may be helpful to explore the various functions for displaying images and understand

what the differences are.

Task 3. In task 2 you essential created a grayscale image as the matrix M(i,j). The values of M(i,j) specifies

the colour of the pixel that is i rows below and j columns to the right of the top left hand corner of

the image. As we only assigned two values any cell in the matrix could be we created a binary image.

A) Now I want you to detect the edges in the image M(i,j). Using the same format as task 2 to

create a condition loop that detects the boundary lines between the 0 and 1 regions of

M(i,j). Display your answer as a new binary image.

B) Now convert your code into a function that can detect edges in an image of any size. Write you code as a function (stack this function at the bottom of your m.file). Test your code on the MATLAB built-in image trees.tif (shown below). Display your answer as a new binary image.

OPTIONAL: Your code should work with the MATLAB test image, but perhaps not very well. Can you think of ways to improve it? MATLAB has sophisticated built-in edge detection functions, you could explore these and compare your results.

Task 4.

The ISO standard Gait cycle for an average person of 70 kg, is provided for you in ‘Gait_data.txt’, which

is available for you on BlackBoard. Download the ‘txt’ file and place it in the same folder as you m.file.

A) Plot the Flextion/extention, Abduction/adduction, and Internal/External rotation over a single

cycle.

B) Plot the Load over a single cycle.

HINT: You will then need to look up the ‘readtable’ functions in order to get the file into MATLAB.

Task 5.

The figure above shows the common configuration of a crank-slider mechanism. If the crank arm, 𝐵𝐶,

has a clockwise rotational speed of 40 rev/sec and the distance 𝐴𝐵⃑⃑⃑⃑ ⃑ = 0.6 m, 𝐵𝐶⃑⃑⃑⃑ ⃑ = 0.1 m, 𝐵𝐺⃑⃑⃑⃑ ⃑ =

0.08 m;

(a) Plot 𝑣𝐴 and 𝑣𝐺 versus time for two revolutions of the crank. And, state the equations for 𝑣𝐴 and

𝑣𝐺.

(b) Plot 𝑎𝐴 and 𝑎𝐺 versus time for two revolutions of the crank. And, state the equations for 𝑎𝐴 and

𝑎𝐺.

HINT: Use trig to find the differential equations you need to solve. Then your life can be made easy by

using the ‘syms’ (symbolic algebra) solver in MATLAB to solve the equations for you. You will then

need to plot your answers in symbolic language using the function plotter (fplot).

Task 6. A ladder lent against a wall is at the point of slipping (shown below). The ladder has a mass of 15 kg

and is released from rest in the position shown at 𝑡 = 0.

A) Neglecting friction, approximate the angular position and angular velocity of the ladder as

functions of time for the first 2 seconds. Using increments 𝛥𝑡 of 0.1, 0.01, 0.001 𝑠.

B) Compare your answer for the angular velocity to the closed form solution;

𝜔 = √3𝑔

𝑙(cos(5) − 𝑐𝑜𝑠𝜃

Plot your answers.

HINT: Draw a freebody diagram of the ladder and apply the equations of motion and determine the

angular acceleration. In your code you may want to use nested loops and use Euler’s method to form

an approximation, you could calculate each time step and input it by hand but this will take a long

time!

** MY FINAL FUNCTION TAKES ~3 SECONDS TO RUN; AND CONTAINS A LITTLE LESS THAN 300 LINES

OF CODE. IF YOU GET LESS THAN THIS WELL DONE!!

IF YOURS IN MUCH LONGER THAN THIS, IT IS NOT A PROBLEM AND DOES NOT COME INTO THE

MARKING. IT MERELY SUGGESTS YOU CAN FIND A MORE EFFICIENT CODE TO SOLVE YOUR PROBLEMS.

IT IS GOOD PRACTICE TO FIND THE FASTEST SOLUTION AS, HOPEFULLY ONE DAY, YOU WILL BE USING

MATLAB (OR SIMILAR) TO SOLVE VERY LARGE AND INVOLVED PROBLEMS THAT TAKE UP EXTENSIVE

COMPUTING POWER AND TIME.