MATLAB Module-3-1 Solutions MATH1052 2017 PDF

Title MATLAB Module-3-1 Solutions MATH1052 2017
Author Joanna Suen
Course Multivariate Calculus & Ordinary Differential Equations
Institution University of Queensland
Pages 9
File Size 538.8 KB
File Type PDF
Total Downloads 12
Total Views 129

Summary

Matlab tutorial solutions and answers for week 3 tutorial of year 2017.
MATLAB Module-3-1 Solutions MATH1052 2017...


Description

11/27/2015

Solutions to Module 3 UQHOME

CONTACTS

STUDY

MAPS

NEWS

EVENTS

L IBRARY

MY.UQ



Index>SolutionstoModule3

SolutionstoModule3 SolutionstotheexercisesforModule3areprovidedbelow.Theanswersyousubmittedfortheexercisesarealsoshown,so thatyoucancompareyouranswerswiththesolutions.

Exercise1 Question Create an executable file that imports and stores the temperaturedataintheWorkspacewithvariablelabel M.Try entering the labels of the objects inside M in the Command Window.Areanyofthevariablesdefined? Yes No Eventhoughthedatahasbeenimporteditisnotreadily accessible. Toaccessvariablesinsideadatastructureweusethesyntax StructureVariable.ObjectVariable. Type commandsintheCommandWindow

the

following

>> disp(M.colheaders{1, 1}),disp(M.data(:, 1) >> M.colheaders{1, 3} Thefirst columnof M.colheadersis thetext "Year",while the first column of M.data are the years corresponding to thetemperaturemeasurementsinthedata. Whichofthefollowingcommandsproducethecolumnvector ofyears?

M.data(1) M.data(:,1) M.data(1,:) Noneoftheabove Syntax:thecommandM.data(:,1)requestsallrowsin thefirstcolumnofthedatasetimportedinMatlabtothe datastructureM. Whatarethefirstandlastyearsrecordedinthedata? Thefirstyearrecordedis: Enter answer 2000 Thelastyearrecordedis: Enter answer 2013 The fifth column in M.colheaders is the text "Apr", while the fifth column in M.data is the mean maximum temperatures of April for each year. Which column correspondstoJanuary? Thesecondcolumn Theeighthcolumn Thethirdcolumn Thefirstcolumn Thesecondcolumnofthedatainthe.xlsxdocumentwas also for the month of January Matlab imports raw data in

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

1/9

11/27/2015

Solutions to Module 3 alsoforthemonthofJanuary.Matlabimportsrawdatain awaythatmatchestheoriginaldata. Which years do the temperatures in M.data(8:10,2:13) correspondto?(selectallthatapply) 2007 2008 2009 2010 2011 Theyears2007,2008,and2009aretheyearsstoredin the8th9thand10throwsofM.data AddthefollowinglinestoyourMfile

months = M.colheaders(2:13); years = M.data(10:14,1); % temps = M.data(?,?); This has defined a vector consisting of the month labels for theyears20092013andavectorconsistingofthoseyearsin chronologicalorder. Checkthis inyour Workspaceorvia the CommandWindow. Add anotherline to yourMfile that defines amatrix labeled

tempswhere eachrow correspondsto theyears 20092013 in chronological order and whose columns give the temperature data corresponding to each month (in chronologicalorder)fortherespectiveyear. Inthefollowingtextbox,providethesinglelineofcommands youjustaddedtoyourMfile No answer submitted

temps=m.data(10:14,2:13)

Tutorcomments No comments given

Exercise2 Question Whatcommandwillalwaysproduceamatrixwhosecolumns aretherowsofA? A' A.' Youmight,therefore,beabletoguessacommandtoplotthe rowsofA.

Tutorcomments No comments given

Exercise3 Question Whichofthefollowingcommandswillplottheentriesofeach columnofthematrixtempsonthesamesetofaxes?

plot(temps) plot(temps.') plot(1:12,temps) plot(years,temps)

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

2/9

11/27/2015

Solutions to Module 3 plot(years,temps) Whichofthefollowingcommandswillplottheentriesofeach rowofthematrixtempsonthesamesetofaxes?

plot(temps) plot(temps.') plot(1:12,temps) plot(years,temps)

Tutorcomments No comments given

Exercise4 Question In the following snippet of Matlab code, the variable names

h1, hXLabel, hYLabel, and hTitle have been used to assignhandles.

meanT = mean(temps);  clf; h1 = plot(meanT.'); % hold on % You can replace this comment with another p % hold off hXLabel = xlabel('Months'); hYLabel = ylabel('Temperature in Celsius ( ^o Which 4 objects of the resultant Figure have we assigned a handleorvariablenameto? Theplotaxes Thetextlabelofthehorizontalaxis Thetextlabeloftheverticalaxis TheTitletext TheFigureWindow Theplotteddata Copy and paste the above code snippet for plotting the averagedmeanmonthlytemperaturesintoyourMfile. InyourMfile,uncommenttheholdcommandsandaddone ofthe plot commandsfrom the listbelow sothat the rows of temps are plotted on the same set of axes as the averaged temperatures. Make sure you include the plot handle h2 and give your plot an appropriate title with the handlehTitle.Selecttheplotcommandyouused:

h2 = plot(temps); h2 = plot(temps.'); h2 = plot(years,temps);

Tutorcomments No comments given

Exercise5 Question Copy and paste the above code snippet into your Mfile and choose a line width that you find appealing. A line width greaterthan4isexcessiveforthistypeofplot.

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

3/9

11/27/2015

Solutions to Module 3 Change the line width, style, and color of the averaged mean monthly temperatures so that it is easily distinguishable from the other data. Once done, copy and pastethe2setcommandsintotheinputbelow: No answer given

Solution The line width used by the mean data with handle h1 shouldbeatleastaslargeasthedatawithhandleh2.The line styles should be different and the colour used for h1 shouldbedistinguishablefromthecoloursusedtoploth2. Thefollowingexamplesnippetusesablackdashedlinefor

h1thatisnoticablythickerthanthelineusedforh2. set(h1,'LineWidth',3,... 'LineStyle','--',... 'Color','k') set(h2,'LineWidth',2)

Tutorcomments No comments given

Exercise6 Question The default axis bounds result in extra space to the left of your plot. Which of the following functions could you use to changetheaxisboundsofyourplot?

axis grid subplot Sinceyouonlyneedtochangethehorizontalboundsyoucan usethe xlimfunction.Editthe xlimfunction inyour Mfile so that all the data is plotted, but without any extra whitespace. No answer given

xlim([112]) Your horizontal tick mark entries have been specified by a vector of text entries, but manually entering such a vector can be tedious. Fortunately, one of your imported data objectswasavectoroftextlabelsdescribingeachcolumnof the temperature data. Which of the following objects holds thisinformation?

months temps years Such a vector can be used directly to assign values to a property. Replace or change the current axis properties

XTickandXTickLabelsothatthehorizontaltickmarks range over all integers from 1 to 12 and their labels are specifiedbytheimportedvectoroftextlabels. Add entries to the set function in your Mfile for each property in the following table. The set function should specifytheparticular settingsforeach propertythatisgiven inthetable. Property

Setting

Description

'Box'

'off'

Display axes as a box

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

4/9

11/27/2015

Solutions to Module 3 Box

off

Displayaxesasabox

'TickDir'

'out'

Specifydirectionofticksacross

'TickLength'

[0.02

theaxis

0.02]

Specifyhorizontalandvertical ticklengths

'YMinorTick

'on'

Displayfractionalverticaltick

'YGrid'

'on'

Displayverticalgridlines

marks

Solution You should now have included the following commands in yourMfile:

% Axis Properties xlim([1 12]) set(gca,'XTick' 'XTickLabel' 'Box' 'TickDir' 'TickLength'

, , , , ,

1:12 months 'off' 'out' [.02 .02]

'YMinorTick' , 'on' 'YGrid' , 'on'

,... ,... ,... ,... ,... ,... );

Tutorcomments No comments given

Exercise7 Question Thecommand legend(['Mean';num2str(years)])will produce a legend whose text entries should correspond to your plot. It has taken the rows of the vector years and converted them from numbers to text, which is the format acceptedby the legendfunction. Add this legend to your Mfile so that it is given the handle hLegend. Provide the commandyouusedinthetextboxbelow. No answer given

hLegend = legend(['Mean';num2str(years)]) Unfortunately, the legend has obscured some of your data. You can change the location of the legend by specifying its

'Location'propertylikeso:

Typedoc legendinthecommandwindowtobringuphelp documentationforthe legend.Thelist oflocationspecifiers should be approximately a third of the way into the document. Try specifying a few different locations from the listandpickonethatyoulikethatdoesn'tobscuretheplotted linesanduseitinyourlegend. Whichspecifierdidyouuse? No answer given

Anyspecifierthatpreventsthedatafrombeingobscuredis acceptable.Someexamplesare:Southeast,

WestOutside, Southwest, North. AddthefollowingcodesnippettoyourMfile

% Adjust font properties set([hLegend, gca] , ... 'FontSize' , 8 ); Describe how this line of code has changed the displayed Figure,makingreference tothefive differenttextsdisplayed onyourfigure,thetitle,the label,the label,the axistick marklabels,andthelegendtext.

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

5/9

11/27/2015

Solutions to Module 3 No answer given

Addingthefollowinglinesofcodewillchangethefontsize oftheaxistickmarklabelsandthelegendtextonly.The fontsizeofthetitleandaxislabelsremainsunchanged.

% Adjust font properties set([hLegend, gca] , ... 'FontSize' , 8 );

Add2moresetfunctionssothatthetitleusesafontsizeof 12andthe labeland  labelusea fontsizeof10. Besure tochangethefontsizesofthe labeland labelandnotthe tickmarklabels!Providethe2setfunctionsyouusedbelow No answer given

Thefollowingcommandswillsetthecorrectfontsizesof the and labelsandtitle.

set([hXLabel, hYLabel] , ... 'FontSize' , 10 ); set( hTitle , ... 'FontSize' , 12 );

Tutorcomments No comments given

Exercise8(optional) Question % Set colours to plot with colormap(lines(length(years))); xtPlot','rep Add the above snippet of code to your Mfile. It must be placedbeforeyouproduceyourfirstplot. Toseealistofsupportedcolormapsenterdoc colormapin the Command Window. When using a predefined colormap you must specify the number of colours to use. Choose a colormapthatyoufindappealingandmakesyourdataeasy todistinguish.Useittoproduceyourplot. There is still one problem. The temperature data for each year has been plotted over the mean data for all years makingithardtosee. To move an object above all other objects you can use the command:

% Bring object to the front uistack(ObjectHandle, 'top') where ObjectHandle is the handle for the given object. Use the handle for plotted mean data for all years to bring the data to the top. You will need to enter the code after your legend has been created, otherwise the lines won't matchtheirlabels.

Solution The following commands could be added to the MFile beforethefirstplotisproduced.

colormap(jet(length(years))); 'NextPlot','r To bring h1 to the front the following command can be addedtotheMfileafterthelegendhasbeencreated.

uistack(h1, 'top')

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

6/9

11/27/2015

Solutions to Module 3

Tutorcomments No comments given

Exercise9(optional) Whenyouchangethedatabeingplotteditistediousworkto changeanylabelsthatmightneedtobespecifictothatdata suchasthetitleofyourplot. Youcanusethesprintffunctiontoprinttextthatincludes data from your workspace. Enter the following command in theCommandWindow.

SomeText =... sprintf('The last two entries in the "year" This has stored as the variable SomeText a statement that has referenced elements of the vector years. The variable

SomeText can be used in place of the text input in plot labelingcommandssuchasxlabel,title,andlegend. Usetextcreatedfromthesprintffunctiontoautomatically produce the years in the title of your plot from the stored variableyears.

Solution To produce the title automatically, you could use the follwoingcommands.

titletext = ... sprintf('Monthly Mean Maximum Temperatures years(1),years(end));

Tutorcomments No comments given

Exercise10 AddthefollowingcommandtoyourMfile.

print('module03.png','-dpng') This command saves your figure as a PNG format image to yourcurrentfolderwiththefilename"module03.png".

UploadyourPNGfigure Click"ChooseFile"andchoosethePNGfiguremodule03.png. Afterwards, click "Upload your PNG", which will upload module03.pngformarking. Finally, click "Choose File" and choose your Mfile. Afterwards,click"UploadyourMfile", whichwilluploadyour updatedscriptformarking.

Solution Hereisanexampleplot:

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

7/9

11/27/2015

Solutions to Module 3

And the commands used to produce it (some commands arepartoftheoptionalexercises):

% Import Data M = importdata('Brisbane_Temp.xlsx');  % Variable Definitions months = M.colheaders(2:13); years = M.data(10:14,1); temps = M.data(10:14,2:13); meanT = mean(temps);  clf; % Order of Colours to Plot (Optional) colormap(jet(length(years))); set(gca,'ColorOrder',colormap,'NextPlot','r  % Plot data h1 = plot(meanT.'); hold on h2 = plot(temps.'); hold off hXLabel = xlabel('Months'); hYLabel = ylabel('Temperature ( ^oC)');  % Title Text (sprintf optional) titletext = ... sprintf('Monthly Mean Maximum Temperatu years(1),years(end)); hTitle = title(titletext); % Plot Line Specifications set(h1,'LineWidth',4 ,... 'LineStyle','--',... 'Color','k') set(h2,'LineWidth',2)  % Legend hLegend = legend(['Mean';num2str(years)],'L  % Bring plot of Mean temperatures for all y uistack(h1, 'top')  % Axis Properties xlim([1 12]) ylim([18 34]) set(gca,'XTick' , 1:12 ,... 'XTickLabel' , months ,... 'Box' , 'off' ,... 'TickDir' , 'out' ,... 'TickLength' , [.02 .02] ,... 'YMinorTick' , 'on' ,... 'YGrid' , 'on' );  % Font Properties set([hLegend, gca] ,... 'FontSize' , 8 ); set([hXLabel, hYLabel] ,... 'FontSize' , 10 ); set( hTitle ,... 'FontSize' , 12 );  % Save Figure as PNG print('module03.png','-dpng')

Tutorcomments No comments given

MarkforModule3 Thissubmissionhasnotbeenmarked.

Markingguidelines Mark

Criteria

5marks

You have demonstrated a thorough understanding of all programming concepts covered in the module, and your answers are free of syntax errors.

4marks

You have demonstrated a thorough understanding of all programming concepts covered in the module, and there are minor syntax errors in youranswers.

3marks

You have demonstrated an understanding of most programming concepts covered in the module, and there are some syntax errors in your answers.

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

8/9

11/27/2015

Solutions to Module 3 youranswers. 2marks

You have not demonstrated a sufficient understanding of programming concepts covered in the module, or not all exercises have been completed.

1mark

You have not demonstrated a sufficient understanding of programming concepts covered in the module, or most exercises haven’t been completed.

0marks

You have not submitted any relevant answers to the exercises for this module.

Clickheretogobacktotheindex.↩

https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3

9/9...


Similar Free PDFs