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 | |
Total Downloads | 12 |
Total Views | 129 |
Matlab tutorial solutions and answers for week 3 tutorial of year 2017.
MATLAB Module-3-1 Solutions MATH1052 2017...
11/27/2015
Solutions to Module 3 UQHOME
CONTACTS
STUDY
MAPS
NEWS
EVENTS
L IBRARY
MY.UQ
Index>SolutionstoModule3
SolutionstoModule3 SolutionstotheexercisesforModule3areprovidedbelow.Theanswersyousubmittedfortheexercisesarealsoshown,so thatyoucancompareyouranswerswiththesolutions.
Exercise1 Question Create an executable file that imports and stores the temperaturedataintheWorkspacewithvariablelabel M.Try entering the labels of the objects inside M in the Command Window.Areanyofthevariablesdefined? Yes No Eventhoughthedatahasbeenimporteditisnotreadily accessible. Toaccessvariablesinsideadatastructureweusethesyntax StructureVariable.ObjectVariable. Type commandsintheCommandWindow
the
following
>> disp(M.colheaders{1, 1}),disp(M.data(:, 1) >> M.colheaders{1, 3} Thefirst columnof M.colheadersis thetext "Year",while the first column of M.data are the years corresponding to thetemperaturemeasurementsinthedata. Whichofthefollowingcommandsproducethecolumnvector ofyears?
M.data(1) M.data(:,1) M.data(1,:) Noneoftheabove Syntax:thecommandM.data(:,1)requestsallrowsin thefirstcolumnofthedatasetimportedinMatlabtothe datastructureM. Whatarethefirstandlastyearsrecordedinthedata? Thefirstyearrecordedis: Enter answer 2000 Thelastyearrecordedis: 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 correspondstoJanuary? Thesecondcolumn Theeighthcolumn Thethirdcolumn Thefirstcolumn Thesecondcolumnofthedatainthe.xlsxdocumentwas 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 alsoforthemonthofJanuary.Matlabimportsrawdatain awaythatmatchestheoriginaldata. Which years do the temperatures in M.data(8:10,2:13) correspondto?(selectallthatapply) 2007 2008 2009 2010 2011 Theyears2007,2008,and2009aretheyearsstoredin the8th9thand10throwsofM.data AddthefollowinglinestoyourMfile
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 theyears20092013andavectorconsistingofthoseyearsin chronologicalorder. Checkthis inyour Workspaceorvia the CommandWindow. Add anotherline to yourMfile that defines amatrix labeled
tempswhere eachrow correspondsto theyears 20092013 in chronological order and whose columns give the temperature data corresponding to each month (in chronologicalorder)fortherespectiveyear. Inthefollowingtextbox,providethesinglelineofcommands youjustaddedtoyourMfile No answer submitted
temps=m.data(10:14,2:13)
Tutorcomments No comments given
Exercise2 Question Whatcommandwillalwaysproduceamatrixwhosecolumns aretherowsofA? A' A.' Youmight,therefore,beabletoguessacommandtoplotthe rowsofA.
Tutorcomments No comments given
Exercise3 Question Whichofthefollowingcommandswillplottheentriesofeach columnofthematrixtempsonthesamesetofaxes?
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) Whichofthefollowingcommandswillplottheentriesofeach rowofthematrixtempsonthesamesetofaxes?
plot(temps) plot(temps.') plot(1:12,temps) plot(years,temps)
Tutorcomments No comments given
Exercise4 Question In the following snippet of Matlab code, the variable names
h1, hXLabel, hYLabel, and hTitle have been used to assignhandles.
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 handleorvariablenameto? Theplotaxes Thetextlabelofthehorizontalaxis Thetextlabeloftheverticalaxis TheTitletext TheFigureWindow Theplotteddata Copy and paste the above code snippet for plotting the averagedmeanmonthlytemperaturesintoyourMfile. InyourMfile,uncommenttheholdcommandsandaddone ofthe plot commandsfrom the listbelow sothat 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 handlehTitle.Selecttheplotcommandyouused:
h2 = plot(temps); h2 = plot(temps.'); h2 = plot(years,temps);
Tutorcomments No comments given
Exercise5 Question Copy and paste the above code snippet into your Mfile and choose a line width that you find appealing. A line width greaterthan4isexcessiveforthistypeofplot.
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 pastethe2setcommandsintotheinputbelow: No answer given
Solution The line width used by the mean data with handle h1 shouldbeatleastaslargeasthedatawithhandleh2.The line styles should be different and the colour used for h1 shouldbedistinguishablefromthecoloursusedtoploth2. Thefollowingexamplesnippetusesablackdashedlinefor
h1thatisnoticablythickerthanthelineusedforh2. set(h1,'LineWidth',3,... 'LineStyle','--',... 'Color','k') set(h2,'LineWidth',2)
Tutorcomments No comments given
Exercise6 Question The default axis bounds result in extra space to the left of your plot. Which of the following functions could you use to changetheaxisboundsofyourplot?
axis grid subplot Sinceyouonlyneedtochangethehorizontalboundsyoucan usethe xlimfunction.Editthe xlimfunction inyour Mfile so that all the data is plotted, but without any extra whitespace. No answer given
xlim([112]) 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 objectswasavectoroftextlabelsdescribingeachcolumnof the temperature data. Which of the following objects holds thisinformation?
months temps years Such a vector can be used directly to assign values to a property. Replace or change the current axis properties
XTickandXTickLabelsothatthehorizontaltickmarks range over all integers from 1 to 12 and their labels are specifiedbytheimportedvectoroftextlabels. Add entries to the set function in your Mfile for each property in the following table. The set function should specifytheparticular settingsforeach propertythatisgiven inthetable. 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
Displayaxesasabox
'TickDir'
'out'
Specifydirectionofticksacross
'TickLength'
[0.02
theaxis
0.02]
Specifyhorizontalandvertical ticklengths
'YMinorTick
'on'
Displayfractionalverticaltick
'YGrid'
'on'
Displayverticalgridlines
marks
Solution You should now have included the following commands in yourMfile:
% Axis Properties xlim([1 12]) set(gca,'XTick' 'XTickLabel' 'Box' 'TickDir' 'TickLength'
, , , , ,
1:12 months 'off' 'out' [.02 .02]
'YMinorTick' , 'on' 'YGrid' , 'on'
,... ,... ,... ,... ,... ,... );
Tutorcomments No comments given
Exercise7 Question Thecommand 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 acceptedby the legendfunction. Add this legend to your Mfile so that it is given the handle hLegend. Provide the commandyouusedinthetextboxbelow. 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'propertylikeso:
Typedoc legendinthecommandwindowtobringuphelp documentationforthe legend.Thelist oflocationspecifiers should be approximately a third of the way into the document. Try specifying a few different locations from the listandpickonethatyoulikethatdoesn'tobscuretheplotted linesanduseitinyourlegend. Whichspecifierdidyouuse? No answer given
Anyspecifierthatpreventsthedatafrombeingobscuredis acceptable.Someexamplesare:Southeast,
WestOutside, Southwest, North. AddthefollowingcodesnippettoyourMfile
% Adjust font properties set([hLegend, gca] , ... 'FontSize' , 8 ); Describe how this line of code has changed the displayed Figure,makingreference tothefive differenttextsdisplayed onyourfigure,thetitle,the label,the label,the axistick marklabels,andthelegendtext.
https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3
5/9
11/27/2015
Solutions to Module 3 No answer given
Addingthefollowinglinesofcodewillchangethefontsize oftheaxistickmarklabelsandthelegendtextonly.The fontsizeofthetitleandaxislabelsremainsunchanged.
% Adjust font properties set([hLegend, gca] , ... 'FontSize' , 8 );
Add2moresetfunctionssothatthetitleusesafontsizeof 12andthe labeland labelusea fontsizeof10. Besure tochangethefontsizesofthe labeland labelandnotthe tickmarklabels!Providethe2setfunctionsyouusedbelow No answer given
Thefollowingcommandswillsetthecorrectfontsizesof the and labelsandtitle.
set([hXLabel, hYLabel] , ... 'FontSize' , 10 ); set( hTitle , ... 'FontSize' , 12 );
Tutorcomments No comments given
Exercise8(optional) Question % Set colours to plot with colormap(lines(length(years))); xtPlot','rep Add the above snippet of code to your Mfile. It must be placedbeforeyouproduceyourfirstplot. Toseealistofsupportedcolormapsenterdoc colormapin the Command Window. When using a predefined colormap you must specify the number of colours to use. Choose a colormapthatyoufindappealingandmakesyourdataeasy todistinguish.Useittoproduceyourplot. There is still one problem. The temperature data for each year has been plotted over the mean data for all years makingithardtosee. 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 matchtheirlabels.
Solution The following commands could be added to the MFile beforethefirstplotisproduced.
colormap(jet(length(years))); 'NextPlot','r To bring h1 to the front the following command can be addedtotheMfileafterthelegendhasbeencreated.
uistack(h1, 'top')
https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3
6/9
11/27/2015
Solutions to Module 3
Tutorcomments No comments given
Exercise9(optional) Whenyouchangethedatabeingplotteditistediousworkto changeanylabelsthatmightneedtobespecifictothatdata suchasthetitleofyourplot. Youcanusethesprintffunctiontoprinttextthatincludes data from your workspace. Enter the following command in theCommandWindow.
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 labelingcommandssuchasxlabel,title,andlegend. Usetextcreatedfromthesprintffunctiontoautomatically produce the years in the title of your plot from the stored variableyears.
Solution To produce the title automatically, you could use the follwoingcommands.
titletext = ... sprintf('Monthly Mean Maximum Temperatures years(1),years(end));
Tutorcomments No comments given
Exercise10 AddthefollowingcommandtoyourMfile.
print('module03.png','-dpng') This command saves your figure as a PNG format image to yourcurrentfolderwiththefilename"module03.png".
UploadyourPNGfigure Click"ChooseFile"andchoosethePNGfiguremodule03.png. Afterwards, click "Upload your PNG", which will upload module03.pngformarking. Finally, click "Choose File" and choose your Mfile. Afterwards,click"UploadyourMfile", whichwilluploadyour updatedscriptformarking.
Solution Hereisanexampleplot:
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 arepartoftheoptionalexercises):
% 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')
Tutorcomments No comments given
MarkforModule3 Thissubmissionhasnotbeenmarked.
Markingguidelines Mark
Criteria
5marks
You have demonstrated a thorough understanding of all programming concepts covered in the module, and your answers are free of syntax errors.
4marks
You have demonstrated a thorough understanding of all programming concepts covered in the module, and there are minor syntax errors in youranswers.
3marks
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 youranswers. 2marks
You have not demonstrated a sufficient understanding of programming concepts covered in the module, or not all exercises have been completed.
1mark
You have not demonstrated a sufficient understanding of programming concepts covered in the module, or most exercises haven’t been completed.
0marks
You have not submitted any relevant answers to the exercises for this module.
Clickheretogobacktotheindex.↩
https://courses.smp.uq.edu.au/MATH1052/modules/solutions.php?module=3
9/9...