COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110Jekyll2018-04-17T12:31:16-05:00http:/ICP2017F/Amir Shahmoradihttp:/ICP2017F/amir@ices.utexas.edu<![CDATA[Homework 6: Solutions - MATLAB data analysis and optimization]]>http:/ICP2017F/homework/6-solutions-matlab-data-analysis-optimization2017-12-13T00:00:00-06:002017-12-13T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="6-problems-matlab-data-analysis-optimization.html" target="_blank">Homework 6: Problems - MATLAB data analysis and optimization</a>.</p>
<!--
The following figure illustrates the grade distribution for this homework.
<figure>
<img src="http:/ICP2017F/homework/gradeDist/gradeHistHomework6.png" width="700">
</figure>
---
---
<br>
-->
<p>♣ <strong>Due Date: Wednesday Dec 13, 2017 9:00 AM</strong>. This homework aims at giving you some experience with image and data analysis and optimization techniques in MATLAB. For this homework, you need to only return two problems of your own choice, out of the three questions. The extra question, if you answer it, will be considered as an extra credit.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> <strong>Subplots in MATLAB.</strong> Consider this MATLAB data file <a href="http:/ICP2017F/homework/6-problems/data3D.mat" target="_blank">data3D.mat</a> which contains a 3-dimensional $41\times 61\times 16$ matrix of the brain of a rat. Write a MATLAB script that creates and saves a graph of all $X-Y$ information for the 16 slices along the z axis like the following.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/subplots.png" width="900" />
</figure>
<p><br /></p>
<p><strong>Hint:</strong> Start from this <a href="http:/ICP2017F/homework/6-problems/hw6prob1.m" target="_blank">MATLAB script</a> that I have written for you. Play with all the options to understand what they do and see their effects on the resulting plot. This script should generate the following figure for you.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/currentPlot.png" width="900" />
</figure>
<p><br /></p>
<p><strong>Answer:</strong></p>
<p>Here is an implementation of this code: <a href="http:/ICP2017F/homework/6-solutions/makeSubplots.m" target="_blank">makeSubplots.m</a>.</p>
<p><br /><br /></p>
<p><strong>2. </strong> <strong>Getting the boundary of objects in images.</strong>. Consider the same dataset as in the previous problem. Write a MATLAB script that delineates the boundary of the tumor in all of the subplots and generates a figure with the tumor boundary highlighted, like the following graph.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/subplotsWithTumorBoundaries.png" width="900" />
</figure>
<p><br /></p>
<p><strong>Answer:</strong></p>
<p>Here is an implementation of this code: <a href="http:/ICP2017F/homework/6-solutions/makeSubplots.m" target="_blank">makeSubplotsWithTumorBoundary.m</a>.</p>
<p><br /><br /></p>
<p><strong>3. </strong> <strong>Regression: obtaining the most likely mean and standard deviation of a set of Standard Normally Distributed Random Variables.</strong> Consider this dataset, <a href="http:/ICP2017F/homework/6-problems/Drand.mat" target="_blank">Drand.mat</a>, which contains a set of random numbers. Let’s make a hypothesis with regards to this dataset: We assume that this dataset is well fit by a <a href="https://en.wikipedia.org/wiki/Normal_distribution" target="_blank">Gaussian distribution</a>. But, we don’t know the values of the two parameters (mean and standard deviation) of this Normal (Gaussian) distribution. Therefore, write a MATLAB script that constructs an objective function (similar to what we are planning to do for the mathematical modeling section of the project) and then uses MATLAB’s built-in function, <code>fminsearch()</code>, to find the most likely values of the mean and standard deviation of this Gaussian distribution. Here is a best-fit Gaussian distribution using the most likely parameters to the histogram of this dataset.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/histfit.png" width="700" />
</figure>
<p><br /></p>
<p><strong>Hints:</strong> Our hypothesis is that the data in this histogram comes from a standard Normal distribution with a fixed mean ($\mu$) and standard deviation ($\sigma$). For the moment, let’s assume that we know the values of these two parameters. Then if all of these points, $D$, come from the normal distribution with the given $(\mu,\sigma)$, then the probability of all them coming from the normal distribution with these parameter values can be computed as,</p>
<script type="math/tex; mode=display">\pi\big(\boldsymbol D\big|\mu,\sigma\big) = \prod^{N=100}_{i=1} \frac{1}{2\pi\sigma^2}\exp\bigg( -\bigg[ \frac{\boldsymbol D(i)-\mu}{\sqrt{2}\sigma} \bigg]^2 \bigg) ~~,</script>
<p>where the symbol $\pi$ to the left of equality means <strong>probability</strong> (but note that $\pi$ on the right hand side of the euqation stands for the number $\pi=3.14\ldots$, and $D(i)$ refers to the $i$th point in the sample of points. Since probabilities are always extremely small numbers, it is always good to work with their <code>log()</code> values instead of their raw values (can you guess why?). Therefore, we could take the log of the above equation to write it as,</p>
<script type="math/tex; mode=display">\log\pi\big(\boldsymbol D\big|\mu,\sigma\big) = \sum^{N=100}_{i=1} - \log\big(2\pi\sigma^2\big) - \bigg[ \frac{\boldsymbol D(i)-\mu}{\sqrt{2}\sigma} \bigg]^2 ~~,</script>
<p>Now our goad is to construct this function (let’s name it <code>getLogProbNorm()</code>) and pass it to MATLAB’s built-in function <code>fminsearch()</code> in order to find the most likely $(\mu,\sigma)$ that leads to the highest likelihood value (the maximum of the above equation). Here is one last tip: Note that <code>fminsearch()</code> minimizes functions, but we want to maximize <code>getLogProbNorm()</code>, instead of minimizing it. What change could you make to this function to make it work with <code>fminsearch()</code>? Name your main script <code>findBestFitParameters.m</code>. Now when you run your script it should call <code>fminsearch()</code> and then output the best-fit parameters like the following,</p>
<pre><code class="language-matlab">>> findBestFitParameters
mu: -0.082001 , sigma: 1.0043
</code></pre>
<p><br />
Start your parameter search via <code>fminsearch()</code> with the following values: $[\mu,\sigma] = [1,10]$.</p>
<p><strong>Answer:</strong></p>
<p>Here is an implementation of this code: <a href="http:/ICP2017F/homework/6-solutions/findBestFitParameters.m" target="_blank">findBestFitParameters.m</a>.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/6-solutions-matlab-data-analysis-optimization">Homework 6: Solutions - MATLAB data analysis and optimization</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on December 13, 2017.</p><![CDATA[Quiz 6: Solutions - MATLAB plotting and Monte Carlo methods]]>http:/ICP2017F/quiz/6-solutions-matlab-plotting-monte-carlo-methods2017-12-11T00:00:00-06:002017-12-11T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="6-problems-matlab-plotting-monte-carlo-methods.html" target="_blank">Quiz 6: Problems - MATLAB plotting and Monte Carlo methods</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p>Since quiz 6 is a protected test, the solutions to the problems will be only discussed in class.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/6-solutions-matlab-plotting-monte-carlo-methods">Quiz 6: Solutions - MATLAB plotting and Monte Carlo methods</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on December 11, 2017.</p><![CDATA[Quiz 6: Problems - MATLAB plotting and Monte Carlo methods]]>http:/ICP2017F/quiz/6-problems-matlab-plotting-monte-carlo-methods2017-12-11T00:00:00-06:002017-12-11T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This quiz is about methods of plotting and Monte Carlo methods using MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<div align="center">
<script>
(function(t,e,s,n){var o,a,c;t.SMCX=t.SMCX||[],e.getElementById(n)||(o=e.getElementsByTagName(s),a=o[o.length-1],c=e.createElement(s),c.type="text/javascript",c.async=!0,c.id=n,c.src=["https:"===location.protocol?"https://":"http://","widget.surveymonkey.com/collect/website/js/tRaiETqnLgj758hTBazgd0AsVRa147JdOaaMwPvLKMOwlOY9Y220uve_2FabyCPgY5.js"].join(""),a.parentNode.insertBefore(c,a))})(window,document,"script","smcx-sdk");
</script>
</div>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/6-problems-matlab-plotting-monte-carlo-methods">Quiz 6: Problems - MATLAB plotting and Monte Carlo methods</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on December 11, 2017.</p><![CDATA[Quiz 5: Solutions - MATLAB IO and plotting]]>http:/ICP2017F/quiz/5-solutions-matlab-IO-plotting2017-12-01T00:00:00-06:002017-12-01T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="5-problems-matlab-IO-plotting.html" target="_blank">Quiz 5: Problems - MATLAB IO and plotting</a>.</p>
<!--
The following figure illustrates the grade distribution for this quiz.
<figure>
<img src="http:/ICP2017F/quiz/gradeDist/gradeHistQuiz4.png" width="700">
<figcaption style="text-align:center">
Maximum possible points is 1.
</figcaption>
</figure>
-->
<p>This quiz is about methods of IO and plotting in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> Write a MATLAB script, named <code>plotGrowthRate.m</code>, that reads this <a href="http:/ICP2017F/quiz/5-problems/chain.txt" target="_blank">chain.txt</a> file, and then makes a plot of the fourth column of data (GrowthRate) in this file, that looks like the following,</p>
<figure>
<img src="http:/ICP2017F/quiz/5-problems/GrowthRate.png" width="700" />
</figure>
<p><br /></p>
<p>Use whatever MATLAB IO method that you prefer, in order to read the data. Save the plot with the name <code>GrowthRate.png</code>.</p>
<p><strong>Answer:</strong></p>
<p>Here is a possible implementation: <a href="http:/ICP2017F/quiz/5-solutions/plotGrowthRate.m" target="_blank">plotGrowthRate.m</a>.</p>
<p><br /><br /></p>
<p><strong>2. </strong> Write a MATLAB script named, <code>robustWebRead.m</code> that takes an input string containing a web address, then checks if the web address exists or not, if it exists, it returns the content of the web page as the output of the function,</p>
<pre><code class="language-matlab">>> d = robustWebRead('https://apod.nasa.gov/apod/image/1711/M33Nagy_tamed.jpg');
Reading data from the web address...
Done.
>> imshow(d)
>>
</code></pre>
<p><br /></p>
<pre><code class="language-matlab">>> robustWebRead('Chicken or egg? which came first? This is the question')
Reading data from the web address...
Warning: The requested web address does not exist! Gracefully exiting...
> In robustWebRead (line 7)
ans =
[]
>>
</code></pre>
<p><br />
otherwise prints a message like the following and exits the function without breaking the MATLAB (e.g., without any abrupt stop).</p>
<p><strong>Answer:</strong></p>
<p>Here is a possible implementation: <a href="http:/ICP2017F/quiz/5-solutions/robustWebRead.m" target="_blank">robustWebRead.m</a>.</p>
<p><br /><br /></p>
<p><strong>3. </strong> What is the difference between <code>gca</code> and <code>gcf</code> keywords in MATLAB? (what does each one do?)</p>
<p><strong>Answer:</strong></p>
<p>The term <code>gca</code> is a MATLAB keyword that refers to the current active plot in the current active figure. By contrast, <code>gcf</code> refers to the current active figure handle.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/5-solutions-matlab-IO-plotting">Quiz 5: Solutions - MATLAB IO and plotting</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on December 01, 2017.</p><![CDATA[Quiz 5: Problems - MATLAB IO and plotting]]>http:/ICP2017F/quiz/5-problems-matlab-IO-plotting2017-12-01T00:00:00-06:002017-12-01T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This quiz is about methods of IO and plotting in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> Write a MATLAB script, named <code>plotGrowthRate.m</code>, that reads this <a href="http:/ICP2017F/quiz/5-problems/chain.txt" target="_blank">chain.txt</a> file, and then makes a plot of the fourth column of data (GrowthRate) in this file, that looks like the following,</p>
<figure>
<img src="http:/ICP2017F/quiz/5-problems/GrowthRate.png" width="700" />
</figure>
<p><br /></p>
<p>Use whatever MATLAB IO method that you prefer, in order to read the data. Save the plot with the name <code>GrowthRate.png</code>.</p>
<p><br /><br /></p>
<p><strong>2. </strong> Write a MATLAB script named, <code>robustWebRead.m</code> that takes an input string containing a web address, then checks if the web address exists or not, if it exists, it returns the content of the web page as the output of the function,</p>
<pre><code class="language-matlab">>> d = robustWebRead('https://apod.nasa.gov/apod/image/1711/M33Nagy_tamed.jpg');
Reading data from the web address...
Done.
>> imshow(d)
>>
</code></pre>
<p><br /></p>
<pre><code class="language-matlab">>> robustWebRead('Chicken or egg? which came first? This is the question')
Reading data from the web address...
Warning: The requested web address does not exist! Gracefully exiting...
> In robustWebRead (line 7)
ans =
[]
>>
</code></pre>
<p><br />
otherwise prints a message like the following and exits the function without breaking the MATLAB (e.g., without any abrupt stop).</p>
<p><br /><br /></p>
<p><strong>3. </strong> What is the difference between <code>gca</code> and <code>gcf</code> keywords in MATLAB? (what does each one do?)</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/5-problems-matlab-IO-plotting">Quiz 5: Problems - MATLAB IO and plotting</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on December 01, 2017.</p><![CDATA[Homework 6: Problems - MATLAB data analysis and optimization]]>http:/ICP2017F/homework/6-problems-matlab-data-analysis-optimization2017-11-27T00:00:00-06:002017-11-27T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>♣ <strong>Due Date: Wednesday Dec 13, 2017 9:00 AM</strong>. This homework aims at giving you some experience with image and data analysis and optimization techniques in MATLAB. For this homework, you need to only return two problems of your own choice, out of the three questions. The extra question, if you answer it, will be considered as an extra credit.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> <strong>Subplots in MATLAB.</strong> Consider this MATLAB data file <a href="http:/ICP2017F/homework/6-problems/data3D.mat" target="_blank">data3D.mat</a> which contains a 3-dimensional $41\times 61\times 16$ matrix of the brain of a rat. Write a MATLAB script that creates and saves a graph of all $X-Y$ information for the 16 slices along the z axis like the following.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/subplots.png" width="900" />
</figure>
<p><br /></p>
<p><strong>Hint:</strong> Start from this <a href="http:/ICP2017F/homework/6-problems/hw6prob1.m" target="_blank">MATLAB script</a> that I have written for you. Play with all the options to understand what they do and see their effects on the resulting plot. This script should generate the following figure for you.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/currentPlot.png" width="900" />
</figure>
<p><br /></p>
<p><br /><br /></p>
<p><strong>2. </strong> <strong>Getting the boundary of objects in images.</strong>. Consider the same dataset as in the previous problem. Write a MATLAB script that delineates the boundary of the tumor in all of the subplots and generates a figure with the tumor boundary highlighted, like the following graph.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/subplotsWithTumorBoundaries.png" width="900" />
</figure>
<p><br /></p>
<p><br /><br /></p>
<p><strong>3. </strong> <strong>Regression: obtaining the most likely mean and standard deviation of a set of Standard Normally Distributed Random Variables.</strong> Consider this dataset, <a href="http:/ICP2017F/homework/6-problems/Drand.mat" target="_blank">Drand.mat</a>, which contains a set of random numbers. Let’s make a hypothesis with regards to this dataset: We assume that this dataset is well fit by a <a href="https://en.wikipedia.org/wiki/Normal_distribution" target="_blank">Gaussian distribution</a>. But, we don’t know the values of the two parameters (mean and standard deviation) of this Normal (Gaussian) distribution. Therefore, write a MATLAB script that constructs an objective function (similar to what we are planning to do for the mathematical modeling section of the project) and then uses MATLAB’s built-in function, <code>fminsearch()</code>, to find the most likely values of the mean and standard deviation of this Gaussian distribution. Here is a best-fit Gaussian distribution using the most likely parameters to the histogram of this dataset.</p>
<figure>
<img src="http:/ICP2017F/homework/6-problems/histfit.png" width="700" />
</figure>
<p><br /></p>
<p><strong>Hints:</strong> Our hypothesis is that the data in this histogram comes from a standard Normal distribution with a fixed mean ($\mu$) and standard deviation ($\sigma$). For the moment, let’s assume that we know the values of these two parameters. Then if all of these points, $D$, come from the normal distribution with the given $(\mu,\sigma)$, then the probability of all them coming from the normal distribution with these parameter values can be computed as,</p>
<script type="math/tex; mode=display">\pi\big(\boldsymbol D\big|\mu,\sigma\big) = \prod^{N=100}_{i=1} \frac{1}{2\pi\sigma^2}\exp\bigg( -\bigg[ \frac{\boldsymbol D(i)-\mu}{\sqrt{2}\sigma} \bigg]^2 \bigg) ~~,</script>
<p>where the symbol $\pi$ to the left of equality means <strong>probability</strong> (but note that $\pi$ on the right hand side of the euqation stands for the number $\pi=3.14\ldots$, and $\boldsymbol D(i)$ refers to the $i$th point in the sample of points. Since probabilities are always extremely small numbers, it is always good to work with their <code>log()</code> values instead of their raw values (can you guess why?). Therefore, we could take the log of the above equation to write it as,</p>
<script type="math/tex; mode=display">\log\pi\big(\boldsymbol D\big|\mu,\sigma\big) = \sum^{N=100}_{i=1} - \log\big(2\pi\sigma^2\big) - \bigg[ \frac{\boldsymbol D(i)-\mu}{\sqrt{2}\sigma} \bigg]^2 ~~,</script>
<p>Now our goad is to construct this function (let’s name it <code>getLogProbNorm()</code>) and pass it to MATLAB’s built-in function <code>fminsearch()</code> in order to find the most likely $(\mu,\sigma)$ that leads to the highest likelihood value (the maximum of the above equation). Here is one last tip: Note that <code>fminsearch()</code> minimizes functions, but we want to maximize <code>getLogProbNorm()</code>, instead of minimizing it. What change could you make to this function to make it work with <code>fminsearch()</code>? Name your main script <code>findBestFitParameters.m</code>. Now when you run your script it should call <code>fminsearch()</code> and then output the best-fit parameters like the following,</p>
<pre><code class="language-matlab">>> findBestFitParameters
mu: -0.082001 , sigma: 1.0043
</code></pre>
<p><br />
Start your parameter search via <code>fminsearch()</code> with the following values: $[\mu,\sigma] = [1,10]$.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/6-problems-matlab-data-analysis-optimization">Homework 6: Problems - MATLAB data analysis and optimization</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 27, 2017.</p><![CDATA[Homework 5: Solutions - MATLAB IO, plotting, and Monte Carlo methods]]>http:/ICP2017F/homework/5-solutions-matlab-IO-plotting-monte-carlo2017-11-27T00:00:00-06:002017-11-27T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="5-problems-matlab-IO-plotting-monte-carlo.html" target="_blank">Homework 5: Problems - MATLAB IO, plotting, and Monte Carlo methods</a>.</p>
<!--
The following figure illustrates the grade distribution for this homework.
<figure>
<img src="http:/ICP2017F/homework/gradeDist/gradeHistHomework5.png" width="700">
</figure>
---
---
<br>
-->
<p>♣ <strong>Due Date: Friday Dec 1, 2017 11:59 PM</strong>. This homework aims at giving you some experience with data input/output methods in MATLAB as well as plotting graphs and Monte Carlo techniques.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> <strong>Creating random 3-member student groups for the semester project</strong> Consider this <a href="http:/ICP2017F/homework/5-problems/students.csv" target="_blank">csv data file</a> which contains the names of all of the students in this course. Our goal here is to write a MATLAB script that reads all the names in this file, and then creates random triples of names to form student groups who would work collaboratively on the final semester project. To do so you will need MATLAB’s built-in function <code>randperm()</code> which creates random permutations of student IDs in the range 1-99. Once you create a random permutation, you will have to write a MATLAB for-loop which takes triples of integers from this vector of random permutations and puts the names corresponding to these IDs together in a cell array. Finally, this cell array of 33-by-3 elements could be written to an output Microsoft xlsx file, using MATLAB’s <code>xlswrite()</code> function. On output your script should yield an excel file like <a href="http:/ICP2017F/homework/5-problems/nameTriples.xlsx" target="_blank">this one</a>. To get the exact same order and triple of names, you will have to use <code>rng(131313)</code> at the beginning of your script in order to initialize the seed of MATLAB random number generator to 131313 so that the table can be regenerated every time you run your code.</p>
<p><strong>Answer:</strong></p>
<p>Here is an implementation of this code: <a href="http:/ICP2017F/homework/5-solutions/pickStudentTriples.m" target="_blank">pickStudentTriples.m</a>.</p>
<p><br /><br /></p>
<p><strong>2. </strong> <strong>Reading scientific data from web using MATLAB</strong>. Consider the following webpage address <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/bat_time_table.html" target="_blank">https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/bat_time_table.html</a>. This is an data table (in HTML language) containing data from <a href="https://www.nasa.gov/mission_pages/swift/main" target="_blank">NASA’s Swift satellite</a>. Each row in this table represents information about a <a href="https://en.wikipedia.org/wiki/Gamma-ray_burst" target="_blank">Gamma-Ray Burst (GRB)</a> detection that Swift has made in the past years. Now, corresponding to each of event IDs, there (might) exist files that contain some attributes of these events which we wish to plot and understand their behavior. For example, for the first event in this table, contains a data file which is hidden in a directory on this website <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/GRB00745966_ep_flu.txt" target="_blank">here</a>. For each event in this table, there is likely one such table hidden in this web directory.</p>
<p>Our goal in this question is to fetch all these files from the website, using MATLAB and save them locally in our own computer. Then read their contents one by one and plot the two columns of data in all of them together.</p>
<p><strong>(A)</strong> Write a MATLAB script named <code>fetchDataFromWeb.m</code> that uses this web address: <code>https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/triggers.txt</code> to read a list of all GRB events and then writes the entire table of <code>triggers.txt</code> to a local file with the same name on your device. For this purpose, you will need MATLAB built-in function <code>webread()</code>.</p>
<p><strong>(B)</strong> Now, add to your script another set of commands that uses the event IDs stored in this file, to generate the corresponding web addresses like: <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/GRB00745966_ep_flu.txt" target="_blank">https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/GRB00745966_ep_flu.txt</a>. Then it uses the generated web address to read the content of the page and store it in a local file on your device with the same name as it is stored on the webpage (for example, for the given webpage, the filename would be <code>GRB00745966_ep_flu.txt</code>). <strong>Note:</strong> Some of the web addresses for the given event IDs do not exist. Therefore, you should MATLAB’s try-catch construct to avoid runtime errors in your MATLAB code.</p>
<p><strong>(C)</strong> Now write another MATLAB script named <code>plotDatafromFile.m</code>, that reads all of these files in your directory, one by one, using MATLAB <code>readtable()</code> function, and plots the content of all of them together, on a single scatter plot (using MATLAB function <code>scatter()</code>) like the following,</p>
<figure>
<img src="http:/ICP2017F/homework/5-problems/SwiftDataPlot.png" width="900" />
</figure>
<p><br /></p>
<p><strong>Note</strong> again that some the data files stored on your computer are empty and some others have useless data if data in the second column of the file is larger than 0. So you will have to write your script in such a way that it checks for non-emptiness of the file (that is, the file does indeed contain some numerical data) as well as the negativity of the values in the column of data in each file. For example, you could check for the negativity of the values using MATLAB function <code>all(data[:,1]<0.0)</code> assuming that data is the variable containing the information read from the file.</p>
<p>Once you have done all these checks, you have to do one final manipulation of data, that is, the data in these files on the second column is actually the log of data, so have to get the <code>exp()</code> value to plot it (because the plot in the figure above is a log-log plot and we want to exactly regenerate it). To do so you could simply use,</p>
<pre><code class="language-matlab">data[:,2] = exp(data[:,2]);
</code></pre>
<p><br />
as soon as you read from the file, and then finally you make a scatter plot of all data using MATLAB scatter plot. At the end, you will have to set a title for your plot as well and label the axes of the plot, and save your plot using MATLAB’s built-in function <code>saveas()</code>. In order to find out how many files you have plotted in the figure, you will have to define a variable counter which increases by one unit, each time a new non-empty negative-second-column data file is read and plotted.</p>
<p><strong>Hint:</strong> I strongly urge you to attend the next three lectures in order to answer this question.</p>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of the two MATLAB scripts: <a href="http:/ICP2017F/homework/5-solutions/fetchDataFromWeb.m" target="_blank">fetchDataFromWeb.m</a> and <a href="http:/ICP2017F/homework/5-solutions/plotDatafromFile.m" target="_blank">plotDatafromFile.m</a>.</p>
<p><br /><br /></p>
<p><strong>3. </strong> <strong>Simulating a fun Monte Carlo game.</strong> Suppose you’re on a game show, and you’re given the choice of three doors:</p>
<figure>
<img src="http:/ICP2017F/homework/5-problems/Monty_1.png" width="600" />
</figure>
<p><br /></p>
<p>Behind one door is a car; behind the two others, goats. You pick a door, say No. 1, and the host of the show opens another door, say No. 3, which has a goat.</p>
<figure>
<img src="http:/ICP2017F/homework/5-problems/Monty_open_door.png" width="600" />
</figure>
<p><br /></p>
<p>He then says to you, “Do you want to pick door No. 2?”.</p>
<p><strong>Question: What would you do?</strong> Is it to your advantage to switch your choice from door 1 to door 2? Is it to your advantage, <strong>in the long run, for a large number of game tries</strong>, to switch to the other door?</p>
<p>Now whatever your answer is, I want you to check/prove your answer by a Monte Carlo simulation of this problem. Make a plot of your simulation for <code>nExperiments=100000</code> repeat of this game, that shows, in the long run, on average, what is the probability of winning this game if you switch your choice, and what is the probability of winning, if you do not switch to the other door.</p>
<p><strong>Hint:</strong> I strongly urge you to attend the lectures this week in order to get help for this question.</p>
<p><br />
<strong>Answer:</strong><br />
An example code can be downloaded from <a href="http:/ICP2017F/homework/5-solutions/monteGame.py" target="_blank">here</a>. Here is the code’s output figure,</p>
<figure>
<img src="http:/ICP2017F/homework/5-solutions/MontyGameResult.png" width="800" />
</figure>
<p><br />
As you see in the figure, although you may initially win by not switching your choice, but in the long run, on average, you will lose, if you don’t switch your choice.</p>
<p><br /><br /></p>
<p><strong>4. </strong> <strong>Monte Carlo approximation of the number $\pi$</strong>. Suppose we did not know the value of $\pi$ and we wanted to estimate its value using Monte Carlo methods. One practical approach is to draw a square of unit side, with its diagonal opposite corners extending from the coordinates origin $(0,0)$ to $(1,1)$. Now we try to simulate uniform random points from inside of this square by generating uniform random points along the $X$ and $Y$ axes, i.e., by generating two random uniform numbers (x,y) from the range $[0,1]$.</p>
<p>Now the generated random point $P$ has the coordinate $(x,y)$, so we can calculate its distance from the coordinate origin. Now suppose we also draw a quarter-circle inside of this square whose radius is unit and is centered at the origin $(0,0)$. The ratio of the area of this quarter-circle, $S_C$ to the area of the area of the square enclosing it, $S_S$ is,</p>
<script type="math/tex; mode=display">\frac{S_C}{S_S} = \frac{\frac{1}{4}\pi r^2}{r^2} = \frac{1}{4}\pi</script>
<p>This is because the area of the square of unit sides, is just 1. Therefore, if we can somehow measure the area of the quarter $S_C$, then we can use the following equation, to get an estimate of $\pi$,</p>
<script type="math/tex; mode=display">\pi = 4S_C</script>
<p>In order to obtain, $S_C$, we are going to throw random points in the square, just as described above, and then find the fraction of points, $f=n_C/n_{\rm total}$, that fall inside this quarter-circle. This fraction is related to the area of the circle and square by the following equation,</p>
<script type="math/tex; mode=display">f=\frac{n_C}{n_{\rm total}} = \frac{S_C}{S_S}</script>
<p>Therefore, one can obtain an estimate of $\pi$ using this fraction,</p>
<script type="math/tex; mode=display">\pi \approx 4\frac{n_C}{n_{\rm total}}</script>
<p>Now, write a MATLAB script, that takes in the number of points to be simulated, and then calculates an approximate value for $\pi$ based on the Monte Carlo algorithm described above. Write a second function that plot the estimate of $\pi$ versus the number of points simulated, like the following,</p>
<figure>
<img src="http:/ICP2017F/homework/5-solutions/approximatePI.png" width="900" />
</figure>
<p><br /></p>
<p><br />
<strong>Answer:</strong><br />
Here is an example MATLAB code that estimates $\pi$: <a href="http:/ICP2017F/homework/5-solutions/estimatePi.m" target="_blank">estimatePi.m</a>.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/5-solutions-matlab-IO-plotting-monte-carlo">Homework 5: Solutions - MATLAB IO, plotting, and Monte Carlo methods</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 27, 2017.</p><![CDATA[Lecture 12: MATLAB - plotting and Monte Carlo methods]]>http:/ICP2017F/lecture/12-matlab-plotting-monte-carlo2017-11-17T00:00:00-06:002017-11-17T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This lecture discusses some of the most important topics in MATLAB plotting, as well as random numbers and Monte Carlo methods in MATLAB.</p>
<div class="post_toc"></div>
<h2 id="lecture-videos">Lecture Videos</h2>
<p>This video is created solely as a reference for the attendants of ICP2017F course at UT Austin. If you did not attend this class, then you may not find this video useful.</p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/je1GEkOkEAY" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/XZ5U5pZv-Wk" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/Akbr8K0bL1k" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/lan-3NsCL7Q" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/rAAjo7jt0po" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<p><br /></p>
<h2 id="curve-plotting-in-matlab">Curve plotting in MATLAB</h2>
<p>One of the most useful methods of outputting the results of your research and MATLAB projects is plotting. MATLAB is truly the unique best language for plotting data, and in my personal view, no other language comes even close to it (except perhaps, the R programming language which is specifically designed for data analysis and plotting). Here in this lecture, we will only review some of the most important and most useful plotting capabilities in MATLAB.</p>
<p><br /><br /></p>
<h3 id="plotting-simple-2d-data">Plotting simple 2D data</h3>
<p>One of the most widely used MATLAB plotting functions is <code>plot()</code>. With this function, plotting x-y data is as simple as it can be. All you need to have is a dataset consisting of X and Y vectors,</p>
<pre><code class="language-matlab">>> X = 0:0.1:10;
>> plot(X,sin(X));
</code></pre>
<p><br />
This will open the following MATLAB figure page for you in the MATLAB environment,</p>
<figure>
<img src="http:/ICP2017F/lecture/12/sin.png" width="700" />
</figure>
<p><br /></p>
<p>You could also save this figure in almost any format you wish using <code>save()</code> function,</p>
<pre><code class="language-matlab">>> saveas(gcf,'sin.png')
</code></pre>
<p><br />
Here, <code>gcf</code> refers tothe current figure handle in MATLAB environment. If you wish to add new data to this plot, you could use <code>hold on;</code> command,</p>
<pre><code class="language-matlab">>> hold on;
>> plot(X,cos(X));
>> saveas(gcf,'sinCos.png')
</code></pre>
<p><br />
This will save the following figure for you, on your local device,</p>
<figure>
<img src="http:/ICP2017F/lecture/12/sinCos.png" width="700" />
</figure>
<p><br /></p>
<h3 id="annotating-and-decorating-your-matlab-plots">Annotating and decorating your MATLAB plots</h3>
<p>Things you can do with MATLAB plotting functions is virtually endless, and there is no way we could cover all of them here in this course. Nevertheless, here are a few useful commands that help you decorate your plots. For example you could add a plot title as well as X-axis and Y-axis labels to your plots by,</p>
<pre><code class="language-matlab">>> title('A simple plot of Sin(x) and Cos(X)', 'fontsize', 12)
>> xlabel('X value', 'fontsize', 13);
>> ylabel('Y value', 'fontsize', 13);
</code></pre>
<p><br />
Also we could add legends to the plot, explaining what each line represents,</p>
<pre><code class="language-matlab">>> legend( { 'Sin(X)' , 'Cos(X)' } , 'fontsize' , 13 , 'location' , 'southwest' );
</code></pre>
<p><br />
Note that the <code>fontsize</code> keyword is not necessary. You could simply omit it and MATLAB’s default font size will be used instead.</p>
<p>You could also change the line-width of the borders of the plot, for example, by,</p>
<pre><code class="language-matlab">>> set( gca , 'linewidth' , 3 );
</code></pre>
<p><br />
Here, <code>gca</code> is a MATLAB keyword that refers to the current active plot in the current active figure. If you wanted to thicken the curve lines themselves, you could simple add the <code>'linewidth'</code> keyword when calling <code>plot()</code>, along with the desired line width value. You could also determine the line color using <code>color</code> keyword followed by the desired color,</p>
<pre><code class="language-matlab">>> hold off; % this closes access to the old figure
>> figure() % this creates a new figure handle
>> plot(X,sin(X),'linewidth',3, 'color', 'blue');
>> hold on;
>> plot(X,cos(X),'linewidth',3, 'color', 'red');
>> legend( { 'Sin(X)' , 'Cos(X)' } , 'fontsize' , 13 , 'location' , 'southwest' );
>> title('A simple plot of Sin(x) and Cos(X)', 'fontsize', 12)
>> xlabel('X value', 'fontsize', 13);
>> ylabel('Y value', 'fontsize', 13);
>> set( gca , 'linewidth' , 3 );
>> saveas(gcf,'sinCosDecorated.png')
</code></pre>
<p><br />
This will generate the following figure and save it to your local hard drive,</p>
<figure>
<img src="http:/ICP2017F/lecture/12/sinCosDecorated.png" width="700" />
</figure>
<p><br /></p>
<p>You can also plot the data using different line/ point styles. For example, to plot the same data using points instead of lines, all you need to do, is to add the <code>'.'</code> string to your <code>plot()</code> functions, indicating that you want a scatter plot, instead of line plot,</p>
<pre><code class="language-matlab">>> figure() % this creates a new figure handle
>> plot(X,sin(X), '.', 'color', 'blue', 'markersize', 20);
>> hold on;
>> plot(X,cos(X), '.', 'color', 'red', 'markersize', 20);
>> legend( { 'Sin(X)' , 'Cos(X)' } , 'fontsize' , 13 , 'location' , 'southwest' );
>> title('A simple plot of Sin(x) and Cos(X)', 'fontsize', 12)
>> xlabel('X value', 'fontsize', 13);
>> ylabel('Y value', 'fontsize', 13);
>> set( gca , 'linewidth' , 3 );
>> saveas(gcf,'sinCosDecoratedScatter.png')
</code></pre>
<p><br />
which will produce and save the following plot,</p>
<figure>
<img src="http:/ICP2017F/lecture/12/sinCosDecoratedScatter.png" width="700" />
</figure>
<p><br /></p>
<p>To learn more about fantastic things you can do with MALTAB plotting functions, see <a href="https://www.mathworks.com/help/matlab/learn_matlab/basic-plotting-functions.html" target="_blank">this page</a>.</p>
<h3 id="other-more-complex-plotting-functions-in-matlab">Other more complex plotting functions in MATLAB</h3>
<p>MATLAB, as said above, has a tremendous set of plotting functions, which make it an ideally suited programming language for scientific research. We will learn how to use some of these functions in homework 5. <a href="https://www.mathworks.com/help/matlab/creating_plots/types-of-matlab-plots.html" target="_blank">Here on this page</a>, you can find a long list of MATLAB plotting functions and types of plots that you can draw using MATLAB.</p>
<h3 id="closing-figures-and-plots-in-matlab">Closing figures and plots in MATLAB</h3>
<p>for closing the current active figure in MATLAB, you could simply use <code>close(gcf)</code>. Here, <code>gcf</code> refers to the current active figure handle. To close all open figures, simply type <code>close all;</code>.</p>
<h2 id="random-numbers-in-matlab">Random numbers in MATLAB</h2>
<p>One of the most important topics in today’s science and computer simulation is random number generation and Monte Carlo simulation methods. In the simplest scenario for your research, you may need to generate a sequence of uniformly distributed random numbers in MATLAB. MATLAB has a large set of built-in functions to handle such random number generation problems. All of these functions are collectively named the <strong>statistics and machine learning toolbox</strong> in MATLAB.</p>
<p>MATLAB has a long list of random number generators. For example, you can use <code>rand()</code> to create a random number in the interval (0,1),</p>
<p>– <code>X = rand</code> returns a single uniformly distributed random number in the interval (0,1).<br />
– <code>X = rand(n)</code> returns an n-by-n matrix of random numbers.<br />
– <code>X = rand(n,m)</code> returns an n-by-m matrix of random numbers.</p>
<p>For example, suppose you generated 10000 uniform random numbers,</p>
<pre><code class="language-matlab">>> RandomValues = rand(10000,1);
</code></pre>
<p><br />
You could test whether the generated random numbers are truly uniformly distributed or not by plotting their histogram,</p>
<pre><code class="language-matlab">>> histogram(RandomValues)
</code></pre>
<p><br />
which will plot the following figure,</p>
<figure>
<img src="http:/ICP2017F/lecture/12/unifrnd.png" width="700" />
</figure>
<p><br /></p>
<p>To generate random integer numbers in a given range, you can use <code>randi()</code> function,</p>
<p>– <code>X = randi(imax)</code> returns a pseudorandom scalar integer between 1 and imax.<br />
– <code>X = randi(imax,n)</code> returns an n-by-n matrix of pseudorandom integers drawn from the discrete uniform distribution on the interval [1,imax].<br />
– <code>X = randi(imax,n,m)</code> returns an n-by-m matrix of pseudorandom integers drawn from the discrete uniform distribution on the interval [1,imax].<br />
– <code>X = randi([imin,imax],n,m)</code> an n-by-m matrix of pseudorandom integers drawn from the discrete uniform distribution on the interval [imin,imax].</p>
<p>For example,</p>
<pre><code class="language-matlab">>> randi([10 23], 3,2)
ans =
20 16
13 17
18 11
</code></pre>
<p><br /></p>
<p>Note that so far, we have only generated uniformly distributed float/integer random numbers. We could however, generate random numbers according to any distribution we wish, that is also supported by MATLAB. For example, a very popular distribution choice, is random number from the <a href="https://en.wikipedia.org/wiki/Normal_distribution" target="_blank">Normal (Gaussian) distribution</a>. To get normally distributed random numbers, you can use MATLAB function <code>randn()</code>,</p>
<p>– <code>X = randn</code> returns a random scalar drawn from the standard normal distribution (mean=0,sigma=1).<br />
– <code>X = randn(n)</code> returns an n-by-n matrix of standard-normally distributed random numbers.<br />
– <code>X = randn(n,m)</code> returns an n-by-m matrix of standard-normally distributed random numbers.</p>
<p>Note that this function generated only <strong>standard</strong>-normally distributed random values. Therefore, a histogram of 10000 of such values produced by <code>randn()</code> would look something like the following,</p>
<pre><code class="language-matlab">>> SNormalValues = randn(10000,1);
>> histogram(SNormalValues);
</code></pre>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/lecture/12/snormrnd.png" width="700" />
</figure>
<p><br /></p>
<p>To get normally distributed random numbers with mean and standard deviation other than the standard normal distribution ($\mu=0,\sigma=1$), you will have to use another MATLAB builtin function <code>normrnd()</code>,</p>
<p>– R = normrnd(mu,sigma) generates random numbers from the normal distribution with mean parameter mu and standard deviation parameter sigma. mu and sigma can be vectors, matrices, or multidimensional arrays that have the same size, which is also the size of R. A scalar input for mu or sigma is expanded to a constant array with the same dimensions as the other input.<br />
– R = normrnd(mu,sigma,m,n,…) or R = normrnd(mu,sigma,[m,n,…]) generates an m-by-n-by-… array. The mu, sigma parameters can each be scalars or arrays of the same size as R.</p>
<pre><code class="language-matlab">NormalValues = normrnd(100, 10, 10000, 1);
>> histogram(NormalValues)
</code></pre>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/lecture/12/normrnd.png" width="700" />
</figure>
<p><br /></p>
<h3 id="the-deterministic-aspect-of-randomness-in-matlab">The deterministic aspect of randomness in MATLAB</h3>
<p>There is a truth about random numbers and random number generators and algorithms, not only in MATLAB, but in all programming languages, and that is, true random numbers do not exist in the world of programming!</p>
<p>What we call a sequence of random numbers, is simply a sequence of numbers that we, the user, to the best of our knowledge, don’t know how it was generated, and therefore, the sequence looks random to us, but not the to the developer of the algorithm!. To prove this, type the following code in a MATLAB session,</p>
<pre><code class="language-matlab">>> rng(135);
>> rand()
ans =
0.8844
>> rand()
ans =
0.0771
>> rand()
ans =
0.5492
>> rand()
ans =
0.8296
</code></pre>
<p><br />
Here, the function <code>rng()</code> controls the random number generation algorithm using the input positive integer number. The truth is that every algorithm for random number generation is deterministic and starts from an input integer number, called the <strong>seed of random number generator</strong>, to construct the sequence of random numbers. This means, that if we set the random number seed to a fixed value before we call the random number generator every time, then we will always get the same fixed random value (in fact, it is not random anymore!),</p>
<pre><code class="language-matlab">>> rng(135);
rand()
ans =
0.6613
>> rng(135);
rand()
ans =
0.6613
>> rng(135);
rand()
ans =
0.6613
>> rng(135);
rand()
ans =
0.6613
</code></pre>
<p><br />
Note that, every time you restart MATLAB, the random number generator seed is set back to the default value, nor matter what you set it to in the last time. This means that every time you open MATLAB, type <code>rand()</code>, you will get the exact same random number as in the last time you opened MATLAB. To avoid this problem, you can use,</p>
<pre><code class="language-matlab">>> rng('shuffle')
</code></pre>
<p><br />
which seeds the random number generator based on the current time in the CPU. Thus, rand, randi, and randn will produce a different sequence of numbers after each time you call rng(‘shuffle’).</p>
<p>Sometimes however, this is not the desired behavior. For example, you want the results of your code to be reproducible. In those cases, it is actually good to initialize the seed of the random number generator in MATLAB to some pre-specified number, so that every time you run your code, you get the exact same result as before. To learn more about the seed of random number generators in MATLAB, visit <a href="https://www.mathworks.com/help/matlab/ref/rng.html?searchHighlight=rng&s_tid=doc_srchtitle" target="_blank">this page</a>.</p>
<h3 id="creating-random-permutation-of-numbers">Creating random permutation of numbers</h3>
<p>There is a useful MATLAB function called <code>randperm()</code> that generates a <a href="https://en.wikipedia.org/wiki/Random_permutation" target="_blank">random permutation</a> of numbers for the user,</p>
<p>– p = randperm(n) returns a row vector containing a random permutation of the integers from 1 to n inclusive.</p>
<p>For example, if we wanted to get a sequence of random numbers within the range from 1 to a given maximum integer $n$, say $n=10$, in an arbitrary order, we could use this function,</p>
<pre><code class="language-matlab">>> randperm(10)
ans =
8 5 2 1 10 6 4 3 9 7
>> randperm(10)
ans =
4 8 1 3 10 2 5 7 9 6
>> randperm(10)
ans =
6 1 2 4 5 8 7 3 10 9
</code></pre>
<p><br />
Note that every time you call the function, you would get a new random permutation of the requested sequence of numbers.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/lecture/12-matlab-plotting-monte-carlo">Lecture 12: MATLAB - plotting and Monte Carlo methods</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 17, 2017.</p><![CDATA[Quiz 4: Solutions - MATLAB loops]]>http:/ICP2017F/quiz/4-solutions-matlab-loops2017-11-13T00:00:00-06:002017-11-13T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="4-problems-matlab-loops.html" target="_blank">Quiz 4: Problems - MATLAB loops</a>.</p>
<p>The following figure illustrates the grade distribution for this quiz.</p>
<figure>
<img src="http:/ICP2017F/quiz/gradeDist/gradeHistQuiz4.png" width="700" />
<figcaption style="text-align:center">
Maximum possible points is 1.
</figcaption>
</figure>
<p>This quiz is about for loops, while loops and vectorization in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> Write a function that takes an input integer, and computes its factorial,</p>
<script type="math/tex; mode=display">n!=n\times (n-1) \times (n-2) \cdots \times 2 \times 1 ~,</script>
<p>in the following ways:</p>
<p>(a) Write this function using while-loop. Name it <code>getFacWhile(n)</code>.</p>
<p>(b) Write this function using for-loop. Name it <code>getFacFor(n)</code>.</p>
<p>(c) Write this function using the vectorization concept. Name it <code>getFacVec(n)</code>. (Hint: for the vectorized version of this function, you will have to first create a vector of integers from 1 to n, using MATLAB vector construction notation (This is very simple and easy if you recall from lecture notes). Then use MATLAB’s built-in <a href="https://www.mathworks.com/help/matlab/ref/prod.html">prod()</a> function to accomplish the task of computing $n!$ as given by the above equation.)</p>
<p><strong>Answer:</strong><br />
Here are the functions: <a href="http:/ICP2017F/quiz/4-solutions/getFacWhile.m" target="_blank">getFacWhile.m</a>, <a href="http:/ICP2017F/quiz/4-solutions/getFacFor.m" target="_blank">getFacFor.m</a>, <a href="http:/ICP2017F/quiz/4-solutions/getFacVec.m" target="_blank">getFacVec.m</a>.<br />
<br /><br /></p>
<p><strong>2. </strong> Write a MATLAB script, <code>timeFacFuncs.m</code> that times the performance of the three functions you wrote in the previous problem, so that when you run this script, you get an output like the following,</p>
<pre><code class="language-matlab">>> timeFacFuncs
average runtime for getFacWhile(1700000): 0.0054129 seconds
average runtime for getFacFor(1700000): 0.0080964 seconds
average runtime for getFacVec(1700000): 0.005283 seconds
</code></pre>
<p><br /></p>
<p><strong>Answer:</strong><br />
Here is the script <a href="http:/ICP2017F/quiz/4-solutions/timeFacFuncs.m" target="_blank">timeFacFuncs.m</a>.<br />
<br /><br /></p>
<p><strong>3. </strong> <strong>Extra Credit</strong> Modify your answer to problem 1.(c) above in such a way that instead of using <code>prod()</code>, you get the factorial using <code>sum()</code> and some other elementary mathematical MATLAB functions. (Hint: for this problem, you will need to transform the numbers involved in calculations using some appropriate MATLAB mathematical function and revert the result at the end.)</p>
<p><strong>Answer:</strong><br />
You can do so, using <code>log()</code> transformation of the numbers in factorial,</p>
<script type="math/tex; mode=display">n! = n\times (n-1) \times \cdots \times 1 ~, \\
\Rightarrow \log(n!) = \log(n) + \log(n-1) + \cdots + \log(1) ~.</script>
<p>Therefore, a possible implementation using <code>sum()</code> could be this function: <a href="http:/ICP2017F/quiz/4-solutions/getFacVecSum.m" target="_blank">getFacVecSum.m</a>.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/4-solutions-matlab-loops">Quiz 4: Solutions - MATLAB loops</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 13, 2017.</p><![CDATA[Quiz 4: Problems - MATLAB loops]]>http:/ICP2017F/quiz/4-problems-matlab-loops2017-11-13T00:00:00-06:002017-11-13T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This quiz is about for loops, while loops and vectorization in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> Write a function that takes an input integer, and computes its factorial,</p>
<script type="math/tex; mode=display">n!=n\times (n-1) \times (n-2) \cdots \times 2 \times 1 ~,</script>
<p>in the following ways:</p>
<p>(a) Write this function using while-loop. Name it <code>getFacWhile(n)</code>.</p>
<p>(b) Write this function using for-loop. Name it <code>getFacFor(n)</code>.</p>
<p>(c) Write this function using the vectorization concept. Name it <code>getFacVec(n)</code>. (Hint: for the vectorized version of this function, you will have to first create a vector of integers from 1 to n, using MATLAB vector construction notation (This is very simple and easy if you recall from lecture notes). Then use MATLAB’s built-in <a href="https://www.mathworks.com/help/matlab/ref/prod.html">prod()</a> function to accomplish the task of computing $n!$ as given by the above equation.)</p>
<p><br /><br /></p>
<p><strong>2. </strong> Write a MATLAB script, <code>timeFacFuncs.m</code> that times the performance of the three functions you wrote in the previous problem, so that when you run this script, you get an output like the following,</p>
<pre><code class="language-matlab">>> timeFacFuncs
average runtime for getFacWhile(1700000): 0.0054129 seconds
average runtime for getFacFor(1700000): 0.0080964 seconds
average runtime for getFacVec(1700000): 0.005283 seconds
</code></pre>
<p><br /><br /></p>
<p><strong>3. </strong> <strong>Extra Credit</strong> Modify your answer to problem 1.(c) above in such a way that instead of using <code>prod()</code>, you get the factorial using <code>sum()</code> and some other elementary mathematical MATLAB functions. (Hint: for this problem, you will need to transform the numbers involved in calculations using some appropriate MATLAB mathematical function and revert the result at the end.)</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/4-problems-matlab-loops">Quiz 4: Problems - MATLAB loops</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 13, 2017.</p><![CDATA[Homework 5: Problems - MATLAB IO, plotting, and Monte Carlo methods]]>http:/ICP2017F/homework/5-problems-matlab-IO-plotting-monte-carlo2017-11-13T00:00:00-06:002017-11-13T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>♣ <strong>Due Date: Friday Dec 1, 2017 11:59 PM</strong>. This homework aims at giving you some experience with data input/output methods in MATLAB as well as plotting graphs and Monte Carlo techniques.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> <strong>Creating random 3-member student groups for the semester project</strong> Consider this <a href="http:/ICP2017F/homework/5-problems/students.csv" target="_blank">csv data file</a> which contains the names of all of the students in this course. Our goal here is to write a MATLAB script that reads all the names in this file, and then creates random triples of names to form student groups who would work collaboratively on the final semester project. To do so you will need MATLAB’s built-in function <code>randperm()</code> which creates random permutations of student IDs in the range 1-99. Once you create a random permutation, you will have to write a MATLAB for-loop which takes triples of integers from this vector of random permutations and puts the names corresponding to these IDs together in a cell array. Finally, this cell array of 33-by-3 elements could be written to an output Microsoft xlsx file, using MATLAB’s <code>xlswrite()</code> function. On output your script should yield an excel file like <a href="http:/ICP2017F/homework/5-problems/nameTriples.xlsx" target="_blank">this one</a>. To get the exact same order and triple of names, you will have to use <code>rng(131313)</code> at the beginning of your script in order to initialize the seed of MATLAB random number generator to 131313 so that the table can be regenerated every time you run your code.</p>
<p><br /><br /></p>
<p><strong>2. </strong> <strong>Reading scientific data from web using MATLAB</strong>. Consider the following webpage address <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/bat_time_table.html" target="_blank">https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/bat_time_table.html</a>. This is an data table (in HTML language) containing data from <a href="https://www.nasa.gov/mission_pages/swift/main" target="_blank">NASA’s Swift satellite</a>. Each row in this table represents information about a <a href="https://en.wikipedia.org/wiki/Gamma-ray_burst" target="_blank">Gamma-Ray Burst (GRB)</a> detection that Swift has made in the past years. Now, corresponding to each of event IDs, there (might) exist files that contain some attributes of these events which we wish to plot and understand their behavior. For example, for the first event in this table, contains a data file which is hidden in a directory on this website <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/GRB00745966_ep_flu.txt" target="_blank">here</a>. For each event in this table, there is likely one such table hidden in this web directory.</p>
<p>Our goal in this question is to fetch all these files from the website, using MATLAB and save them locally in our own computer. Then read their contents one by one and plot the two columns of data in all of them together.</p>
<p><strong>(A)</strong> Write a MATLAB script named <code>fetchDataFromWeb.m</code> that uses this web address: <code>https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/triggers.txt</code> to read a list of all GRB events and then writes the entire table of <code>triggers.txt</code> to a local file with the same name on your device. For this purpose, you will need MATLAB built-in function <code>webread()</code>.</p>
<p><strong>(B)</strong> Now, add to your script another set of commands that uses the event IDs stored in this file, to generate the corresponding web addresses like: <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/GRB00745966_ep_flu.txt" target="_blank">https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/swift/GRB00745966_ep_flu.txt</a>. Then it uses the generated web address to read the content of the page and store it in a local file on your device with the same name as it is stored on the webpage (for example, for the given webpage, the filename would be <code>GRB00745966_ep_flu.txt</code>). <strong>Note:</strong> Some of the web addresses for the given event IDs do not exist. Therefore, you should MATLAB’s try-catch construct to avoid runtime errors in your MATLAB code.</p>
<p><strong>(C)</strong> Now write another MATLAB script named <code>plotDatafromFile.m</code>, that reads all of these files in your directory, one by one, using MATLAB <code>readtable()</code> function, and plots the content of all of them together, on a single scatter plot (using MATLAB function <code>scatter()</code>) like the following,</p>
<figure>
<img src="http:/ICP2017F/homework/5-problems/SwiftDataPlot.png" width="900" />
</figure>
<p><br /></p>
<p><strong>Note</strong> again that some the data files stored on your computer are empty and some others have useless data if data in the second column of the file is larger than 0. So you will have to write your script in such a way that it checks for non-emptiness of the file (that is, the file does indeed contain some numerical data) as well as the negativity of the values in the column of data in each file. For example, you could check for the negativity of the values using MATLAB function <code>all(data[:,1]<0.0)</code> assuming that data is the variable containing the information read from the file.</p>
<p>Once you have done all these checks, you have to do one final manipulation of data, that is, the data in these files on the second column is actually the log of data, so have to get the <code>exp()</code> value to plot it (because the plot in the figure above is a log-log plot and we want to exactly regenerate it). To do so you could simply use,</p>
<pre><code class="language-matlab">data[:,2] = exp(data[:,2]);
</code></pre>
<p><br />
as soon as you read from the file, and then finally you make a scatter plot of all data using MATLAB scatter plot. At the end, you will have to set a title for your plot as well and label the axes of the plot, and save your plot using MATLAB’s built-in function <code>saveas()</code>. In order to find out how many files you have plotted in the figure, you will have to define a variable counter which increases by one unit, each time a new non-empty negative-second-column data file is read and plotted.</p>
<p><strong>Hint:</strong> I strongly urge you to attend the next three lectures in order to answer this question.</p>
<p><br /><br /></p>
<p><strong>3. </strong> <strong>Simulating a fun Monte Carlo game.</strong> Suppose you’re on a game show, and you’re given the choice of three doors:</p>
<figure>
<img src="http:/ICP2017F/homework/5-problems/Monty_1.png" width="600" />
</figure>
<p><br /></p>
<p>Behind one door is a car; behind the two others, goats. You pick a door, say No. 1, and the host of the show opens another door, say No. 3, which has a goat.</p>
<figure>
<img src="http:/ICP2017F/homework/5-problems/Monty_open_door.png" width="600" />
</figure>
<p><br /></p>
<p>He then says to you, “Do you want to pick door No. 2?”.</p>
<p><strong>Question: What would you do?</strong> Is it to your advantage to switch your choice from door 1 to door 2? Is it to your advantage, <strong>in the long run, for a large number of game tries</strong>, to switch to the other door?</p>
<p>Now whatever your answer is, I want you to check/prove your answer by a Monte Carlo simulation of this problem. Make a plot of your simulation for <code>nExperiments=100000</code> repeat of this game, that shows, in the long run, on average, what is the probability of winning this game if you switch your choice, and what is the probability of winning, if you do not switch to the other door.</p>
<p><strong>Hint:</strong> I strongly urge you to attend the lectures this week in order to get help for this question.</p>
<p><br /><br /></p>
<p><strong>4. </strong> <strong>Monte Carlo approximation of the number $\pi$</strong>. Suppose we did not know the value of $\pi$ and we wanted to estimate its value using Monte Carlo methods. One practical approach is to draw a square of unit side, with its diagonal opposite corners extending from the coordinates origin $(0,0)$ to $(1,1)$. Now we try to simulate uniform random points from inside of this square by generating uniform random points along the $X$ and $Y$ axes, i.e., by generating two random uniform numbers (x,y) from the range $[0,1]$.</p>
<p>Now the generated random point $P$ has the coordinate $(x,y)$, so we can calculate its distance from the coordinate origin. Now suppose we also draw a quarter-circle inside of this square whose radius is unit and is centered at the origin $(0,0)$. The ratio of the area of this quarter-circle, $S_C$ to the area of the area of the square enclosing it, $S_S$ is,</p>
<script type="math/tex; mode=display">\frac{S_C}{S_S} = \frac{\frac{1}{4}\pi r^2}{r^2} = \frac{1}{4}\pi</script>
<p>This is because the area of the square of unit sides, is just 1. Therefore, if we can somehow measure the area of the quarter $S_C$, then we can use the following equation, to get an estimate of $\pi$,</p>
<script type="math/tex; mode=display">\pi = 4S_C</script>
<p>In order to obtain, $S_C$, we are going to throw random points in the square, just as described above, and then find the fraction of points, $f=n_C/n_{\rm total}$, that fall inside this quarter-circle. This fraction is related to the area of the circle and square by the following equation,</p>
<script type="math/tex; mode=display">f=\frac{n_C}{n_{\rm total}} = \frac{S_C}{S_S}</script>
<p>Therefore, one can obtain an estimate of $\pi$ using this fraction,</p>
<script type="math/tex; mode=display">\pi \approx 4\frac{n_C}{n_{\rm total}}</script>
<p>Now, write a MATLAB script, that takes in the number of points to be simulated, and then calculates an approximate value for $\pi$ based on the Monte Carlo algorithm described above. Write a second function that plot the estimate of $\pi$ versus the number of points simulated, like the following,</p>
<figure>
<img src="http:/ICP2017F/homework/5-solutions/approximatePI.png" width="900" />
</figure>
<p><br /></p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/5-problems-matlab-IO-plotting-monte-carlo">Homework 5: Problems - MATLAB IO, plotting, and Monte Carlo methods</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 13, 2017.</p><![CDATA[Homework 4: Solutions - loops, IO]]>http:/ICP2017F/homework/4-solutions-loops-IO2017-11-13T00:00:00-06:002017-11-13T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="4-problems-loops-IO.html" target="_blank">Homework 4: Problems - loops, IO</a>.</p>
<p>The following figure illustrates the grade distribution for this homework.</p>
<figure>
<img src="http:/ICP2017F/homework/gradeDist/gradeHistHomework4.png" width="700" />
<figcaption style="text-align:center">
</figcaption>
</figure>
<hr />
<hr />
<p><br /></p>
<p>♣ <strong>Due Date: Monday Nov 13, 2017 9:00 AM</strong>. This homework aims at giving you some experience with MATLAB for-loops and while-loops as well as input/output functionalities in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> <strong>The while-loop implementation of a for-loop.</strong> Consider the following two vectors of temperatures in Celsius degrees to Fahrenheit, using a for-loop and then prints them on screen.</p>
<pre><code class="language-matlab">Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]
Fdegrees = [-20, -15, -5, 0, 10, 15, 30, 35, 40]
</code></pre>
<p><br />
(A) Write a function that takes an input vector of temperatures, and a string which is either <code>'F2C'</code> or <code>C2F</code>. Then, converts the input temperature vector from Fahrenheit to Celsius if the input string is <code>'F2C'</code>, otherwise converts the input temperature vector from Celsius to Fahrenheit if the input string is <code>'C2F'</code>, otherwise outputs an error message and aborts the program.</p>
<p>(A) Write this function using while-loop construct (you can name the function <code>convertTempFor.m</code>).<br />
(B) Write this function using for-loop construct (you can name the function <code>convertTempWhile.m</code>).<br />
(C) Write this function using vectorization concept (you can name the function <code>convertTempVec.m</code>).</p>
<p>Here are some example calls to these functions,</p>
<pre><code class="language-matlab">InVec = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40];
>> convertTempFor(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
>> convertTempWhile(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
>> convertTempVec(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
</code></pre>
<p><br /></p>
<p><strong>Answer:</strong></p>
<p>Here are the three <a href="http:/ICP2017F/homework/4-solutions/convertTempFor.m" target="_blank">convertTempFor.m</a>, <a href="http:/ICP2017F/homework/4-solutions/convertTempWhile.m" target="_blank">convertTempWhile.m</a>, and <a href="http:/ICP2017F/homework/4-solutions/convertTempVec.m" target="_blank">convertTempVec.m</a> functions.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>2. </strong> Use MATLAB built-in timing functions to measure the performance of three functions you wrote in question 1 above.</p>
<p><strong>Answer:</strong><br />
Here is <a href="http:/ICP2017F/homework/4-solutions/timing.m" target="_blank">one way (timing.m script)</a> to time the functions. Here is a test result:</p>
<pre><code class="language-matlab">>> timing
Timing for convertTempVec: 0.038723 seconds.
Timing for convertTempFor: 0.03936 seconds.
Timing for convertTempWhile: 0.18011 seconds.
</code></pre>
<p><br /></p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>3. </strong> Consider the following nested cell vector,</p>
<pre><code class="language-matlab">List = { {'M','A','T','L','A','B'}, {' '}, {'i','s'}, {' '}, {'a'}, {' '}, {'s','t','r','a','n','g','e'}, {', '}, {'b','u','t',' '}, {'p','o','p','u','l','a','r'}, {' '}, {'p','r','o','g','r','a','m','m','i','n','g',' ','l','a','n','g','u','a','g','e'} };
</code></pre>
<p><br />
Write a MATLAB script <code>extractLetter.m</code> that uses for-loop to extract all the letters in the variable list and finally prints them all as a single string like the following,</p>
<pre><code class="language-matlab">>> extractLetter
MATLAB is a strange, but popular programming language
</code></pre>
<p><br /></p>
<p><strong>Answer:</strong><br />
Here is an <a href="http:/ICP2017F/homework/4-solutions/extractLetter.m" target="_blank">example implementation</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>4. </strong> <strong>The significant impact of round-off errors in numerical computation.</strong> Consider the following program,</p>
<pre><code class="language-python">formatSpec = 'With %d sqrt, then %d times ^2 operations, the number %.16f becomes: %.16f \n'; % the string format for fprintf function
for n = 1:60
r_original = 2.0;
r = r_original;
for i = 1:n
r = sqrt(r);
end
for i = 1:n
r = r^2;
end
fprintf(formatSpec,n,n,r_original,r);
end
</code></pre>
<p><br />
Explain what this code does. Then run the code, and explain why do you see the behavior observed. In particular, why do you not recover the original value $2.0$ after many repetitions of the same forward and reverse task of taking square root and squaring the result?</p>
<p><strong>Answer:</strong><br />
This code (<code>roundoff.m</code>) will yield the following output:</p>
<pre><code class="language-text">>> roundoff
With 1 sqrt, then 1 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000000004
With 2 sqrt, then 2 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999999996
With 3 sqrt, then 3 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999999996
With 4 sqrt, then 4 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999999964
With 5 sqrt, then 5 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999999964
With 6 sqrt, then 6 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999999964
With 7 sqrt, then 7 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999999714
With 8 sqrt, then 8 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000000235
With 9 sqrt, then 9 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000000235
With 10 sqrt, then 10 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000000235
With 11 sqrt, then 11 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000000235
With 12 sqrt, then 12 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999991336
With 13 sqrt, then 13 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999973292
With 14 sqrt, then 14 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999973292
With 15 sqrt, then 15 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999999973292
With 16 sqrt, then 16 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000117746
With 17 sqrt, then 17 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000408580
With 18 sqrt, then 18 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000000408580
With 19 sqrt, then 19 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000001573586
With 20 sqrt, then 20 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000001573586
With 21 sqrt, then 21 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000001573586
With 22 sqrt, then 22 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000010885857
With 23 sqrt, then 23 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000029511749
With 24 sqrt, then 24 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000066771721
With 25 sqrt, then 25 times ^2 operations, the number 2.0000000000000000 becomes: 2.0000000066771721
With 26 sqrt, then 26 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999917775542
With 27 sqrt, then 27 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999917775542
With 28 sqrt, then 28 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999917775542
With 29 sqrt, then 29 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999917775542
With 30 sqrt, then 30 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999917775542
With 31 sqrt, then 31 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999999917775542
With 32 sqrt, then 32 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999990380770896
With 33 sqrt, then 33 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999971307544144
With 34 sqrt, then 34 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999971307544144
With 35 sqrt, then 35 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999971307544144
With 36 sqrt, then 36 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999971307544144
With 37 sqrt, then 37 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999971307544144
With 38 sqrt, then 38 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999360966436217
With 39 sqrt, then 39 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999360966436217
With 40 sqrt, then 40 times ^2 operations, the number 2.0000000000000000 becomes: 1.9999360966436217
With 41 sqrt, then 41 times ^2 operations, the number 2.0000000000000000 becomes: 1.9994478907329654
With 42 sqrt, then 42 times ^2 operations, the number 2.0000000000000000 becomes: 1.9984718365144798
With 43 sqrt, then 43 times ^2 operations, the number 2.0000000000000000 becomes: 1.9965211562778555
With 44 sqrt, then 44 times ^2 operations, the number 2.0000000000000000 becomes: 1.9965211562778555
With 45 sqrt, then 45 times ^2 operations, the number 2.0000000000000000 becomes: 1.9887374575497223
With 46 sqrt, then 46 times ^2 operations, the number 2.0000000000000000 becomes: 1.9887374575497223
With 47 sqrt, then 47 times ^2 operations, the number 2.0000000000000000 becomes: 1.9887374575497223
With 48 sqrt, then 48 times ^2 operations, the number 2.0000000000000000 becomes: 1.9887374575497223
With 49 sqrt, then 49 times ^2 operations, the number 2.0000000000000000 becomes: 1.8682459487159784
With 50 sqrt, then 50 times ^2 operations, the number 2.0000000000000000 becomes: 1.6487212645509468
With 51 sqrt, then 51 times ^2 operations, the number 2.0000000000000000 becomes: 1.6487212645509468
With 52 sqrt, then 52 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 53 sqrt, then 53 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 54 sqrt, then 54 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 55 sqrt, then 55 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 56 sqrt, then 56 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 57 sqrt, then 57 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 58 sqrt, then 58 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 59 sqrt, then 59 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
With 60 sqrt, then 60 times ^2 operations, the number 2.0000000000000000 becomes: 1.0000000000000000
</code></pre>
<p><br />
What is happening is that, 1 is returned for n >= 52 as square root of 2, that is, after 52 times square-root operation, the degree of accuracy required for representing the result goes beyond the degree of accuracy available in a MATLAB double precision number. Consequently, the later squaring operation on 1.00000000000000 will leave the number unchanged and therefore, 2 is not recovered.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>5. </strong> Consider the following code,</p>
<pre><code class="language-matlab">eps = 1.0;
while 1.0 ~= 1.0 + eps
disp(num2str(eps));
eps = eps / 2.0;
end
disp(['final eps:', num2str(eps)]);
</code></pre>
<p><br /><br />
Explain what the code is doing. Run the code and observe the output. How could <code>1.0 ~= 1.0 + eps</code> be <code>false</code>?!</p>
<p><strong>Answer:</strong><br />
Here is the output of the code,</p>
<pre><code class="language-text">>> epsError
eps: 1
eps: 0.5
eps: 0.25
eps: 0.125
eps: 0.0625
eps: 0.03125
eps: 0.015625
eps: 0.0078125
eps: 0.0039063
eps: 0.0019531
eps: 0.00097656
eps: 0.00048828
eps: 0.00024414
eps: 0.00012207
eps: 6.1035e-05
eps: 3.0518e-05
eps: 1.5259e-05
eps: 7.6294e-06
eps: 3.8147e-06
eps: 1.9073e-06
eps: 9.5367e-07
eps: 4.7684e-07
eps: 2.3842e-07
eps: 1.1921e-07
eps: 5.9605e-08
eps: 2.9802e-08
eps: 1.4901e-08
eps: 7.4506e-09
eps: 3.7253e-09
eps: 1.8626e-09
eps: 9.3132e-10
eps: 4.6566e-10
eps: 2.3283e-10
eps: 1.1642e-10
eps: 5.8208e-11
eps: 2.9104e-11
eps: 1.4552e-11
eps: 7.276e-12
eps: 3.638e-12
eps: 1.819e-12
eps: 9.0949e-13
eps: 4.5475e-13
eps: 2.2737e-13
eps: 1.1369e-13
eps: 5.6843e-14
eps: 2.8422e-14
eps: 1.4211e-14
eps: 7.1054e-15
eps: 3.5527e-15
eps: 1.7764e-15
eps: 8.8818e-16
eps: 4.4409e-16
eps: 2.2204e-16
final eps:1.1102e-16
</code></pre>
<p><br />
What is happening is that after a certain number of divisions performed on the value of <code>eps</code>, the value goes beyond the highest float precision representable by Python standard ($0.0000000000000001$), and therefore the value of <code>eps</code> is eventually rounded to exact zero. The nonzero <code>eps</code> value computed above is called <strong>machine epsilon</strong> or <strong>machine zero</strong> and is an important parameter to know, since it can lead to disasters in your very important complex calculations.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>6. </strong> Suppose you want to find the largest prime number that is smaller than a given input value by the user. Write a function named <code>getLargestPrime</code> that does so, using for-loop, break, and MATLAB’s intrinsic function isprime(). Here is a test,</p>
<pre><code class="language-matlab">>> getLargestPrime(123)
ans =
113
</code></pre>
<p><br /></p>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">function integer = getLargestPrime(upper)
if (upper<1)
disp('input value cannot be less than 1. Goodbye!')
return
end
for integer = upper:-1:1
if isprime(integer)
break
end
end
end
</code></pre>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>6. </strong> Consider the problem number 5 in HW 3, where we wrote a <a href="http:/ICP2017F/homework/3/fib.m">function</a> named <code>fib.m</code> that used the idea of recursive functions to generate the Fibonacci numbers.</p>
<p>(A) Download <a href="http:/ICP2017F/homework/3/fib.m" target="_blank">this function fib()</a> and modify it using MATLAB <code>timeit()</code> function such that it also returns the average runtime of <code>getFib()</code> nested function inside <code>fib()</code>, right after giving the requested Fibonacci number. For example, here is an output from such modified code:</p>
<pre><code class="language-matlab">>> fib
Please enter a non-negative integer or type stop: 10
fib(10) = 55
average runtime: 1.0083e-05 seconds
Please enter a non-negative integer or type stop: 15
fib(15) = 610
average runtime: 8.8884e-05 seconds
Please enter a non-negative integer or type stop: 20
fib(20) = 6765
average runtime: 0.00095559 seconds
Please enter a non-negative integer or type stop: 25
fib(25) = 75025
average runtime: 0.010311 seconds
Please enter a non-negative integer or type stop: 30
fib(30) = 832040
average runtime: 0.11575 seconds
Please enter a non-negative integer or type stop: 35
fib(35) = 9227465
average runtime: 1.2904 seconds
Please enter a non-negative integer or type stop: stop
</code></pre>
<p><br />
(Note that you can use <code>char(9)</code> at the beginning of your <code>disp()</code> messages in order to add the <code>tab</code> character at the beginning of your message, just like the above example.)</p>
<p>(B) Now copy this function to a new MATLAB M-file named <code>fibLoop.m</code>. Also modify the name of the function <code>fib()</code> in this file <code>fibLoop()</code>. Modify the nested function <code>getFib()</code> inside of <code>fibLoop()</code> such that instead of recursive function calls, it uses a for-loop to find the requested Fibonacci number.</p>
<p>(C) Now time your new function <code>fibLoop()</code> for the same input integers as in the above example: $10,15,20,25,30,35$. How do the runtimes for <code>fibLoop()</code> compare with <code>fib()</code>. Which function is faster and more efficient: <code>fib()</code> or <code>fibLoop()</code>? Why is there such huge difference in the performance of the two functions?</p>
<p><strong>Answer:</strong></p>
<p>Here is an implementation of the <a href="http:/ICP2017F/homework/4/fib.m" target="_blank">modified fib()</a> and <a href="http:/ICP2017F/homework/4/fibLoop.m" target="_blank">modified fib()</a>.</p>
<pre><code class="language-matlab">>> fibLoop
Please enter a non-negative integer or type stop: 12
fib(12) = 144
average runtime: 4.3496e-06 seconds
Please enter a non-negative integer or type stop: 10
fib(10) = 55
average runtime: 4.5323e-06 seconds
Please enter a non-negative integer or type stop: 15
fib(15) = 610
average runtime: 4.5232e-06 seconds
Please enter a non-negative integer or type stop: 20
fib(20) = 6765
average runtime: 4.6357e-06 seconds
Please enter a non-negative integer or type stop: 25
fib(25) = 75025
average runtime: 4.6562e-06 seconds
Please enter a non-negative integer or type stop: 30
fib(30) = 832040
average runtime: 4.7624e-06 seconds
Please enter a non-negative integer or type stop: 35
fib(35) = 9227465
average runtime: 4.7889e-06 seconds
Please enter a non-negative integer or type stop: stop
</code></pre>
<p><br />
As you see, the for-loop version of the function <code>fibLoop()</code> is far faster than the recursive function version <code>fib()</code>. The reason is that the recursive version is not well written and does a lot of redundant calculations. Ask me in class to explain for you why there is such a huge redundancy in this function calculations.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>7. </strong> <strong>(A)</strong> Write two new MATLAB functions <code>timeFib(n)</code> and <code>timeFibLoop(n)</code> based on your MATLAB functions <code>fib()</code> and <code>fibLoop()</code> that you wrote in problem 6, such that both take an integer and output a structure whose fields are:</p>
<pre><code class="language-matlab">output.n
output.fib
output.runtime
</code></pre>
<p><br />
Note that the function should take as input only an integer variable, so you need to modify your old codes to only check whether the input <code>~ischar()</code>, and <code>isreal()</code> and <code>n>=0</code> and <code>round(n)==n</code>. Here is an example output from the two functions,</p>
<pre><code class="language-matlab">>> timeFib(20)
ans =
n: 20
fib: 6765
runtime: 9.6568e-04
>> timeFib('amir')
Error using timeFib (line 8)
The input argument is not a non-negative integer!
>> timeFibLoop(20)
ans =
n: 20
fib: 6765
runtime: 4.4076e-06
>> timeFibLoop('amir')
Error using timeFibLoop (line 8)
The input argument is not a non-negative integer!
</code></pre>
<p><br />
<strong>(B)</strong> Now write a script named <code>writeFibResult.m</code> that calls these two functions for a range of input $n={10,2,3,\ldots,35}$ values, and then write the output of these two functions in a formatted way in two files like these <a href="http:/ICP2017F/homework/4-problems/fibOutput.txt" target="_blank">fibOutput.txt</a> and <a href="http:/ICP2017F/homework/4-problems/fibLoopOutput.txt" target="_blank">fibLoopOutput.txt</a>. You can use any of MATLAB IO methods to create the output file with any file extension you prefer: <code>.txt</code>, <code>.csv</code>, <code>.xlsx</code>, <code>.tab</code>, … .</p>
<p><strong>Answer:</strong></p>
<p>Here the two functions <a href="http:/ICP2017F/homework/4-solutions/timeFib.m" target="_blank">timeFib.m</a> and <a href="http:/ICP2017F/homework/4-solutions/timeFibLoop.m" target="_blank">timeFibLoop.m</a>, and here is the script <a href="http:/ICP2017F/homework/4-solutions/writeFibResult.m" target="_blank">writeFibResult.m</a> that creates the requested output file in the problem.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/4-solutions-loops-IO">Homework 4: Solutions - loops, IO</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 13, 2017.</p><![CDATA[Exam final: semester project]]>http:/ICP2017F/exam/1-semester-project2017-11-13T00:00:00-06:002017-11-13T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is page describes the final semester project that will serve as the final exam for this course. Please submit all your efforts for this project (all files, data and results) in <code>ICP2017F/exams/final/</code> directory in your private repository for this course. Don’t forget to push your answers to your remote Github repository by <strong>Friday 9 AM, Dec 15 2017</strong>. **Note: I strongly urge you to attend the future lectures until the end of the semester and seek help from the instructor (Amir) to tackle this project.</p>
<p>Inside the directory for the project (<code>ICP2017F/exams/final/</code>) create three other folders: <code>data</code>, <code>src</code>, <code>results</code>. The <code>data</code> folder contains the <a href="http:/ICP2017F/exam/1-problems/cells.mat" target="_blank">input data</a> for this project. The <code>src</code> folder should contain all your codes that you write for this project, and the <code>results</code> folder should contain all the results generated by your code.</p>
<div class="post_toc"></div>
<h2 id="data-reduction-and-visualization">Data reduction and visualization</h2>
<p>Our goal in this project is to fit a mathematical model of the growth of living cells to real experimental data for the growth of a cancer tumor in the brain of a rat. You can download the data in the form of a MATLAB data file for this project from <a href="http:/ICP2017F/exam/1-problems/cells.mat" target="_blank">here</a>. Write a set of separate MATLAB codes that perform the following tasks one after the other, and output all the results to the <code>results</code> folder described above. Since you have multiple MATLAB codes each in a separate file for different purposes, you should also write a <code>main.m</code> MATLAB code, such that when the user of your codes runs on MATLAB command line,</p>
<pre><code class="language-bash">>> main
</code></pre>
<p><br />
then all the necessary MATLAB codes to generate all the results will be called by this <code>main.m</code> script.</p>
<p>Initially at time $t=0 ~\mathrm{[days]}$, $100,000\pm10,000$ brain tumor cells are injected to the brain of the rat. These cells are then allowed to grow for 10 days. Then starting at day 10, the brain of the rat is imaged using an <a href="https://en.wikipedia.org/wiki/Magnetic_resonance_imaging" target="_blank">MRI machine</a>.</p>
<p>Each image results in a 4-dimensional double-precision MATLAB matrix <code>cells(:,:,:,:)</code>, corresponding to dimensions <code>cells(y,x,z,time)</code>. This data is collected from MRI imaging of the rat’s brain almost every other day for a period of two weeks. For example, <code>cells(:,:,:,1)</code> contains the number of cells at each point in space (y,x,z) at the first time point, or, <code>cells(:,:,10,1)</code> represents a (XY) slice of MRI at $z=1$ and $t=1 [days]$.</p>
<p>Therefore, the vector of times at which we have the number of tumor cells measured would be,</p>
<script type="math/tex; mode=display">Time = [ 0, 10, 12, 14, 16, 18, 20, 22 ] ~,</script>
<p>in units of days. Given this data set,</p>
<p><strong>1. </strong> First write a MATLAB script that reads the input MATLAB file containing cell numbers at different positions in the rat’s brain measured by MRI, on different days.</p>
<p><strong>2. </strong> Write MATLAB codes that generate a set of figures as similar as possible to the following figures (specific color-codes of the curves and figures do not matter, focus more on the format of the plots and its parts). For this part of the project you will MATLAB plotting functions such as <code>plot()</code>, <code>imagesc()</code> and the concept subplots in MATLAB.</p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/tvccZSliceSubplotWithXYlab_rad_00gy_1_t10.0.png" width="900" />
</figure>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/tvccZSliceSubplotWithXYlab_rad_00gy_2_t12.0.png" width="900" />
</figure>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/tvccZSliceSubplotWithXYlab_rad_00gy_3_t14.0.png" width="900" />
</figure>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/tvccZSliceSubplotWithXYlab_rad_00gy_5_t16.0.png" width="900" />
</figure>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/tvccZSliceSubplotWithXYlab_rad_00gy_6_t18.0.png" width="900" />
</figure>
<p><br /></p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/tvccZSliceSubplotWithXYlab_rad_00gy_7_t20.0.png" width="900" />
</figure>
<p><br /></p>
<h2 id="obtaining-the-error-in-tumor-cell-count">Obtaining the error in tumor cell count</h2>
<p><strong>3. </strong> Our assumption here is that the uncertainty in the total number of tumor cells at each time point is given by the number of tumor cells at the boundary of tumor. Therefore, you will have to write a MATLAB code that identifies the boundary of tumor at each time point and then sums over the count cells in all boundary points and uses that as the error in number of tumor cell counts. For this part, you will need MATLAB functions such as <code>bwboundaries()</code> and <code>errorbar()</code>. In the end, you should get and save a figure in your project’s figure folder like the following figure,</p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/growthCurve.png" width="900" />
</figure>
<p><br /></p>
<p>Note that this part of the project is completely independent of the modeling part described in the following section.</p>
<h2 id="the-mathematical-model-of-tumor-growth">The mathematical model of tumor growth</h2>
<p><strong>4. </strong> Now our goal is to fit the time evolution of the growth of this tumor, using a mathematical model. To do so, we need to find the best-fit parameters of the model. The mathematical model we will use here is called the <a href="https://en.wikipedia.org/wiki/Gompertz_function" target="_blank">Gompertzian growth model</a>. Here, we will use a slightly modified for of the Gompertzian function of the following form,</p>
<script type="math/tex; mode=display">N(t,\lambda,c) = N_0 \times \exp\bigg( \lambda~\bigg[ 1-\exp(-ct) \bigg] \bigg) ~,</script>
<p>where $N(t,\lambda,c)$ is the <strong>predicted number</strong> of tumor cells at time $t$, $N_0$ is the initial number of tumor cells at time $t=0$ days, $\lambda$ is the growth rate parameter of the model, and $c$ is just another parameter of the model. We already know the initial value of the number of tumor cells, $N_0=100,000\pm10,000$. Therefore, we can fix $N_0$ to $100,000$ in the equation of the model given above.</p>
<p>However, we don’t know the values of the parameters $\lambda$ and $c$. Thus, we would like to find their best values given the input tumor cell data using some MATLAB optimization algorithm.</p>
<p>This Gompertzian growth model is called our <strong>physical model</strong> for this problem, because it describes the physics of our problem (The physics/biology of the tumor growth).</p>
<h3 id="combining-the-physical-model-with-a-regression-model">Combining the physical model with a regression model</h3>
<p>Now, if our physical model was ideally perfect in describing the data, the curve of the model prediction would pass through all the points in the growth curve plot of the above figure, thus providing a prefect description of data. This is however, never the case, as it is famously said <strong>all models are wrong, but some are useful</strong>. In other words, the model prediction never matches observation perfectly.</p>
<p>Therefore, we have to seek for the parameter values that can bring the model prediction us as close as possible to data. To do so, we define a <strong>statistical model</strong> in addition to the <strong>physical model</strong> described above. In other words, we have to define a statistical regression model (the renowned <strong>least-squares method</strong>) that gives us the probability $\pi(\log N_{obs}|\log N(t))$ of observing individual data points at each of the given times,</p>
<script type="math/tex; mode=display">\pi(\log N_{obs} | \log N(t,\lambda,c),\sigma) = \frac{1}{\sigma\sqrt{2\pi}} \exp\bigg( - \frac{ \big[ \log N_{obs}(t)-\log N(t,\lambda,c) \big]^2}{2\sigma^2} \bigg) ~,</script>
<p>Note that our statistical model given above is a Normal probability density function, with its mean parameter represented by <strong>the log</strong> of the output of our physical model, $\log N(t,\lambda,c)$, and its standard deviation represented by $\sigma$, which is unknown, and we seek to find it. The symbol $\pi$, whenever it appears with parentheses, like $\pi()$, it means probability of the entity inside the parentheses. However, whenever it appears alone, it means the famous number PI, $\pi\approx 3.1415$.</p>
<p><strong>Why do we use the logarithm of the number of cells instead of using the number of cells directly?</strong> The reason behind it is slightly complicated. A simple (but not entirely correct argument) is the following: We do so, because the tumor cell counts at later times become extremely large numbers, on the order of several million cells (For example, look at the number of cells in the late stages of the tumor growth, around $t=20$ days). Therefore, to make sure that we don’t hit any numerical precision limits of the computer when dealing with such huge numbers, we work with the logarithm of the number of tumor cells instead of their true non-logarithmic values.</p>
<p>We have seven data points, so the overall probability of observing all of data $\mathcal{D}$ together (the time vector and the logarithm of the number of cells at different times) given the parameters of the model, $\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)$, is the product of their individual probabilities of observations given by the above equation,</p>
<script type="math/tex; mode=display">% <![CDATA[
\begin{align*}
\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)
&= \prod_{i=1}^{n=8} \pi(\log N_{obs}(t_i) | \log N(t_i,\lambda,c),\sigma) \\\\
&= \prod_{i=1}^{n=8} \frac{1}{\sigma\sqrt{2\pi}} \exp\bigg( - \frac{ \big[ \log N_{obs}(t_i)-\log N(t_i,\lambda,c) \big]^2}{2\sigma^2} \bigg) ~.
\end{align*} %]]></script>
<p>Frequently however, you would want to work with $\log\mathcal{L}$ instead of $\mathcal{L}$. This is again because the numbers involved are extremely small often below the precision limits of the computer. So, by taking the logarithm of the numbers, we work instead with number’s exponent, which looks just like a normal number (not so big, not so small). So, by taking the log, the above equation becomes,</p>
<script type="math/tex; mode=display">% <![CDATA[
\begin{align*}
\log\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)
&= \sum_{i=1}^{n=8} \log \pi( \log N_{obs}(t_i) | \log N(t_i,\lambda,c),\sigma) \\\\
&= \sum_{i=1}^{n=8} \log \bigg[ \frac{1}{\sigma\sqrt{2\pi}} \exp\bigg( - \frac{ \big[ \log N_{obs}(t_i) - \log N(t_i,\lambda,c) \big]^2}{2\sigma^2} \bigg) \bigg] ~.
\end{align*} %]]></script>
<p><br /></p>
<p><strong>5. </strong>
Now the goal is to use an optimization algorithm in MATLAB, such as <code>fminsearch()</code>, to find the most likely set of the parameters of the model $\lambda,c,\sigma$ that give the highest likelihood of obtaining the available data, which is given by the number $\log\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)$ from the above equation. So we want to find the set of parameters for which this number given by the above equation is maximized. You can also use any MATLAB optimization function or method that you wish, to obtain the best parameters.</p>
<p>However, if you use <code>fminsearch()</code>, then note that this function finds the minimum of an input function, not the maximum. What we want is to find the maximum of $\log\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)$.
What is the solution then? Very simple.
We can multiply the value of $\log\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)$ by a negative, so that the maximum value is converted to minimum. But, note that the position (the set of parameter values) at which this minimum occurs, will remain the same as the maximum position for $\log\mathcal{L}(\mathcal{D}|\lambda,c,\sigma)$.</p>
<p>So, now rewrite your likelihood function above by multiplying its final result (which is just number) by a negative sign. Then you pass this modified function to <code>fminsearch()</code> and you find the optimal parameters. Note that <code>fminsearch()</code> takes as input also a set of initial staring parameter values to initiate the search for the optimal parameters. You can use $(\lambda,c,\sigma) = [10,0.1,1]$ as your starting point given to <code>fminsearch()</code> to search for the optimal values of the parameters.</p>
<p>Then redraw the above tumor evolution curve and show the result from the model prediction as well, like the following,</p>
<figure>
<img src="http:/ICP2017F/exam/1-problems/figures/growthCurveFit.png" width="900" />
</figure>
<p><br /></p>
<p>Report also your best fit parameters in a file and submit them with all the figures and your codes to your exam folder repository.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/exam/1-semester-project">Exam final: semester project</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 13, 2017.</p><![CDATA[Lecture 11: MATLAB - Input/Output (IO)]]>http:/ICP2017F/lecture/11-matlab-IO2017-11-08T00:00:00-06:002017-11-08T00:00:00-06:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This lecture discusses topics on data Input/Output processes in MATLAB.</p>
<div class="post_toc"></div>
<h2 id="lecture-videos">Lecture Videos</h2>
<p>This video is created solely as a reference for the attendants of ICP2017F course at UT Austin. If you did not attend this class, then you may not find this video useful.</p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/fcHoYAeiKiI" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/jPWAtLfQthI" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<p><br /></p>
<p>So far in this course, we have indirectly discussed several methods of getting input information from the user, and several methods of outputting the result in a MATLAB program. This lecture, attempts at formalizing all the previous discussions and introduce more general efficient methods of code interaction with users.</p>
<h2 id="methods-of-data-inputoutput-in-matlab">Methods of data input/output in MATLAB</h2>
<p>Let’s begin with an example code, explaining the meaning of input/output (I/O) in MATLAB,</p>
<pre><code class="language-python">a = 0.1;
b = 1;
x = 0.6;
y = a*exp(b*x)
</code></pre>
<pre><code>0.1822
</code></pre>
<p>In the above code, <code>a</code>, <code>b</code>, <code>x</code> are examples of input data to a code, and <code>y</code> is an example of code output. In such cases as in the above, the input data is said to be <strong>hardcoded</strong> in the program.</p>
<blockquote>
<b>NOTE</b><br /><br />
<b>In general, in any programming language, including MATLAB, you should avoid hardcoding input information to your program as much as possible.</b><br /><br />
If data is hardcoded, then every time that it needs to be changed, the user has to change the content of the code. This is not considered good programming style for software development.
</blockquote>
<p><br />
In general, input data can be fed to a program in four different ways:</p>
<ol>
<li>let the user answer questions in a dialog in <strong>MATLAB terminal window</strong>,</li>
<li>let the user provide input on the <strong>operating system command line</strong>,</li>
<li>let the user write input data in a <strong>graphical interface</strong>,</li>
<li>let the user provide input data in a <strong>file</strong>.</li>
</ol>
<p>For outputting data, there are two major methods,</p>
<ul>
<li>writing to the terminal window, as previously done using print() function, or,</li>
<li>writing to an output file.</li>
</ul>
<p>We have already extensively discussed printing output to the terminal window. Reading from and writing data to file is also easy as we see in this lecture.</p>
<h3 id="inputoutput-from-matlab-terminal-window">Input/output from MATLAB terminal window</h3>
<p>We have already introduced and used this method frequently in previous lectures, via the MATLAB’s built-in function <code>input()</code>. If we were to get the input data for the above code via the terminal window, an example approach would be the following,</p>
<pre><code class="language-matlab">datain = input('input [a,b,c]: ');
a = datain(1);
b = datain(2);
x = datain(3);
y = a*exp(b*x)
</code></pre>
<pre><code>input a,b,c: [0.1, 1, 0.6]
y =
0.1822
</code></pre>
<p>One could also read the input values as string ans then convert them to real values or parse the input using one of MATLAB’s built-in functions, for example,</p>
<pre><code class="language-matlab">>> datain = input('input [a,b,c]: ','s');
input [a,b,c]: [0.1, 1, 0.6]
>> class(datain)
ans =
char
>> datain = str2num(datain)
datain =
0.1000 1.0000 0.6000
>> class(datain)
ans =
double
>> a = datain(1);
>> b = datain(2);
>> x = datain(3);
>> y = a*exp(b*x)
y =
0.1822
</code></pre>
<p><br /></p>
<h3 id="inputoutput-data-from-operating-systems-command-line">Input/output data from operating system’s command line</h3>
<p>This approach is most popular in Unix-like environments, where most users are accustomed to using Bash command line. However, it can be readily used in <a href="https://en.wikipedia.org/wiki/Cmd.exe" target="_blank">Windows cmd</a> environment as well. For this approach, we have to invoke MATLAB from the computer operating system’s command line, that is, Bash in Linux systems, and cmd in Windows,</p>
<pre><code class="language-bash">start matlab -nosplash -nodesktop -r "testIO
</code></pre>
<p><br />
Then a MATLAB command-line window opens in your computer like the following that runs automatically your code (stored in <code>testIO.m</code>).</p>
<figure>
<img src="http:/ICP2017F/lecture/11/matlab.png" width="900" />
</figure>
<p><br />
In the above command, we are basically starting MATLAB from the OS command line with our own choice of optional arguments for MATLAB. You can specify startup options (also called <strong>command flags</strong> or <strong>command-line switches</strong>) that instruct the MATLAB program to perform certain operations when you start it. On all platforms, specify the options as arguments to the matlab command when you start at the operating system prompt. For example, the following starts MATLAB and suppresses the display of the splash screen (a splash screen is a graphical control element consisting of a window containing an image, a logo, and the current version of the software. A splash screen usually appears while a game or program is launching),</p>
<pre><code class="language-matlab">matlab -nosplash
</code></pre>
<p><br />
The flag <code>-nodesktop</code> result in opening only the MATLAB command line, and no MATLAB Graphical user interface (GUI) just like the figure above. Finally, the flag <code>-r</code> executes the MATLAB file that appears right after it, specified as a string or as the name of a MATLAB script or function. If statement is MATLAB code, you should enclose the string with double quotation marks. If statement is the name of a MATLAB function or script, <strong>do not specify the file extension</strong> and <strong>do not use quotation marks</strong>. Any required file must be on the MATLAB search path or in the startup folder. You can also set MATLAB’s working folder right from the command-line using <code>-sd</code> flag. You can find find more information about all possible flags <a href="https://www.mathworks.com/help/matlab/ref/matlabwindows.html" target="_blank">here</a>. On Windows platforms, you can precede a startup option with either a hyphen (<code>-</code>) or a slash (<code>/</code>). For example, <code>-nosplash</code> and <code>/nosplash</code> are equivalent.</p>
<p>Note that you can also quote MATLAB on the OS command line, along with the name of the script you want to run. For example, suppose you wanted to run the original script,</p>
<pre><code class="language-matlab">a = 0.1;
b = 1;
x = 0.6;
y = a*exp(b*x)
</code></pre>
<p><br />
but now with <code>a</code>, <code>b</code>, <code>x</code>, given at runtime. You could write a script file <code>test.m</code> that contains,</p>
<pre><code class="language-matlab">y = a*exp(b*x)
</code></pre>
<p><br />
and give the variables values at runtime, on OS command line, like the following,</p>
<pre><code class="language-bash">matlab -nosplash -nodesktop -r "a = 0.1; b = 1; x = 0.6; testIO"
</code></pre>
<p><br />
The figure below shows a screen-shot illustrarting the output of the above command.</p>
<figure>
<img src="http:/ICP2017F/lecture/11/matlab1.png" width="900" />
</figure>
<p><br /></p>
<h3 id="inputoutput-data-from-a-graphical-user-interface">Input/output data from a Graphical User Interface</h3>
<p>This method of inputting data is done by constructing a Graphical User Interface (GUI) which opens and takes input from the user. This is probably one of the most convenient methods for the users to input data. You can do this in MATLAB for example by using the built-in function <code>inputdlg()</code> which creates dialog box that gathers user input. But this method of data colleciton is beyond the scope of our class. More information about this can be found <a href="https://www.mathworks.com/help/matlab/ref/inputdlg.html" target="_blank">here</a>.</p>
<h3 id="inputoutput-data-from-file">Input/output data from file</h3>
<p>In cases where the input/output data is large, the command-line arguments and input from terminal window are not efficient anymore. In such cases, the most common approach is to let the code read/write data from a pre-existing file, the path to which is most often given to the code via the OS command line or MATLAB terminal window.</p>
<p>There are many methods of importing and exporting data to and from MATLAB, only some of which we will discuss here. For more information see <a href="https://www.mathworks.com/help/matlab/import_export/ways-to-import-text-files.html" target="_blank">here</a>, <a href="https://www.mathworks.com/help/matlab/data-import-and-export.html" target="_blank">here</a>, and <a href="https://www.mathworks.com/help/matlab/text-files.html" target="_blank">here</a>. The following table shows some of the most important import functions in MATLAB, which we will discuss here as well.</p>
<table class="center">
<caption class="title" style="padding-bottom:10px;text-align:center;">
Table of Common Methods for Importing Data from a File to MATLAB.
</caption>
<thead>
<tr>
<th><font size="4rm" color="red">Function</font></th>
<th><font size="4rm" color="red">Description</font></th>
</tr>
</thead>
<tbody>
<tr><td><code>load() </code></td><td> Load MATLAB variables from file into MATLAB workspace</td></tr>
<tr><td><code>save() </code></td><td> save MATLAB variables from MATLAB workspace into a MATLAB `.mat` file.</td></tr>
<tr><td><code>fscanf() </code></td><td> Read data from text file</td></tr>
<tr><td><code>fprintf() </code></td><td> Write data to a text file</td></tr>
<tr><td><code>dlmread() </code></td><td> Read ASCII-delimited file of numeric data into matrix</td></tr>
<tr><td><code>dlmwrite() </code></td><td> Write a numeric matrix into ASCII-delimited file</td></tr>
<tr><td><code>csvread() </code></td><td> Read comma-separated value (CSV) file</td></tr>
<tr><td><code>csvwrite() </code></td><td> Write values of a matrix into a comma-separated (CSV) file</td></tr>
<tr><td><code>xlswrite() </code></td><td> Read Microsoft Excel spreadsheet file</td></tr>
<tr><td><code>xlswrite() </code></td><td> write data into a Microsoft Excel spreadsheet file</td></tr>
<tr><td><code>readtable() </code></td><td> Create table from file</td></tr>
<tr><td><code>writetable() </code></td><td> Write table to file</td></tr>
<tr><td><code>imread() </code></td><td> Read image from graphics file</td></tr>
<tr><td><code>imwrite() </code></td><td> Write image to graphics file</td></tr>
<tr><td><code>importdata() </code></td><td> Load data from file</td></tr>
<tr><td><code>textscan() </code></td><td> Read formatted data from text file or string</td></tr>
<tr><td><code>fgetl() </code></td><td> Read line from file, removing newline characters</td></tr>
<tr><td><code>fread() </code></td><td> Read data from binary file</td></tr>
<tr><td><code>fwrite() </code></td><td> Write data to binary file</td></tr>
<tr><td><code>type() </code></td><td> Display contents of file</td></tr>
</tbody>
</table>
<p><br /></p>
<h4 id="loadingsaving-matlab-workspace-variables">Loading/saving MATLAB workspace variables</h4>
<p>MATLAB has two useful functions that can save the workspace variables into special MATLAB <code>.mat</code> files, to be later load again into the same or another MATLAB workspace for further work or manipulation. The function <code>save()</code> saves workspace variables to a given file. The most useful options for this function are the following,</p>
<pre><code class="language-matlab">save(filename)
save(filename,variables)
save(filename,variables,fmt)
</code></pre>
<p><br /></p>
<ul>
<li><code>save(filename)</code> saves all variables from the current workspace in a MATLAB formatted binary file called <strong>MAT-file</strong> with the given name <code>filename</code>. If the file <code>filename</code> exists, <code>save()</code> overwrites the file.<br />
<br /></li>
<li><code>save(filename,variables)</code> saves only the variables or fields of a structure array specified by <code>variables</code>. For example,
<pre><code class="language-matlab">p = rand(1,10);
q = ones(10);
save('pqfile.mat','p','q')
</code></pre>
<p><br />
will create the binary MAT file <a href="http:/ICP2017F/lecture/11/pqfile.mat" target="_blank">pqfile.mat</a> which contains the two variables.<br />
<br /></p>
</li>
<li><code>save(filename,variables,fmt)</code> saves the requested variables with the file format specified by <code>fmt</code>. The variables argument is optional. If you do not specify variables, the save function saves all variables in the workspace. File format, specified as one of the following. When using the command form of save, you do not need to enclose the input in single or double quotes, for example, save myFile.txt -ascii -tabs.</li>
</ul>
<table class="center">
<caption class="title" style="padding-bottom:10px;text-align:center;">
Table of Common Methods for Importing Data from a File to MATLAB.
</caption>
<thead>
<tr>
<th><font size="4rm" color="red">Value of fmt</font></th>
<th><font size="4rm" color="red">File Format</font></th>
</tr>
</thead>
<tbody>
<tr><td><code>'-mat'</code></td><td>Binary MAT-file format.</td></tr>
<tr><td><code>'-ascii'</code></td><td>Text format with 8 digits of precision.</td></tr>
<tr><td><code>'-ascii','-tabs'</code></td><td>Tab-delimited text format with 8 digits of precision.</td></tr>
<tr><td><code>'-ascii','-double'</code></td><td>Text format with 16 digits of precision.</td></tr>
<tr><td><code>'-ascii','-double','-tabs'</code></td><td>Tab-delimited text format with 16 digits of precision.</td></tr>
</tbody>
</table>
<p><br /></p>
<p>For example,</p>
<pre><code class="language-matlab">p = rand(1,10);
q = ones(10);
save('pqfile.txt','p','q','-ascii')
</code></pre>
<p><br />
will create an ASCII text file <a href="http:/ICP2017F/lecture/11/pqfile.txt" target="_blank">pqfile.txt</a> which contains the two variables <code>p</code> and <code>q</code>.</p>
<p>Similarly, one can reload the same files into MATLAB workspace again if needed, for example using MATLAB <code>load()</code> function,</p>
<pre><code class="language-matlab">>> load('pqfile.txt')
>> pqfile
pqfile =
Columns 1 through 8
0.0975 0.2785 0.5469 0.9575 0.9649 0.1576 0.9706 0.9572
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000
Columns 9 through 10
0.4854 0.8003
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
1.0000 1.0000
</code></pre>
<p><br />
But note that upon loading the Ascii file, the information about the individual variables is lost. By contrast, loading data using the MAT file will preserve the variables structure,</p>
<pre><code class="language-matlab">>> load('pqfile.mat')
>> p
p =
Columns 1 through 8
0.1419 0.4218 0.9157 0.7922 0.9595 0.6557 0.0357 0.8491
Columns 9 through 10
0.9340 0.6787
>> q
q =
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
</code></pre>
<p><br /></p>
<h4 id="readingwriting-a-formatted-file-using-fscanf-and-fprintf">Reading/writing a formatted file using <code>fscanf()</code> and <code>fprintf()</code></h4>
<p>There are numerous methods of reading the contents of a file in MATLAB. The most trivial and probably least pleasing method is through MATLAB’s built-in function <code>fscanf()</code>. To read a file, say <a href="http:/ICP2017F/lecture/11/data.in" target="_blank">this file</a>, you will have to first open it in MATLAB,</p>
<pre><code class="language-matlab">fileID = fopen('data.in','r');
formatSpec = '%f';
A = fscanf(fileID,formatSpec)
fclose(fileID);
</code></pre>
<pre><code>A =
1
3
4
5
6
7
88
65
</code></pre>
<p>Note that unlike the C language’s <code>fscanf()</code>, in MATLAB <code>fscanf()</code> is vectorized meaning that it can read multiple lines all at once. Here, the attribute <code>'r'</code> states that the file is opened for the purpose of reading it (vs writing, or some other purpose). A list of available options for <code>fopen()</code> are the following,</p>
<table class="center">
<caption class="title" style="padding-bottom:10px;text-align:center;">
Table of Attributes for MATLAB function <code>fopen()</code>.
</caption>
<thead>
<tr>
<th><font size="4rm" color="red">Attribute</font></th>
<th><font size="4rm" color="red">Description</font></th>
</tr>
</thead>
<tbody>
<tr><td><code>'r' </code></td><td>Open file for reading.</td></tr>
<tr><td><code>'w' </code></td><td>Open or create new file for writing. Discard existing contents, if any.</td></tr>
<tr><td><code>'a' </code></td><td>Open or create new file for writing. Append data to the end of the file.</td></tr>
<tr><td><code>'r+'</code></td><td>Open file for reading and writing.</td></tr>
<tr><td><code>'w+'</code></td><td>Open or create new file for reading and writing. Discard existing contents, if any.</td></tr>
<tr><td><code>'a+'</code></td><td>Open or create new file for reading and writing. Append data to the end of the file.</td></tr>
<tr><td><code>'A' </code></td><td>Open file for appending without automatic flushing of the current output buffer.</td></tr>
<tr><td><code>'W' </code></td><td>Open file for writing without automatic flushing of the current output buffer.</td></tr>
</tbody>
</table>
<p><br /></p>
<p>The general syntax for reading an array from an input file using <code>fscanf()</code> is the following,</p>
<pre><code class="language-matlab">array = fscanf(fid,format)
[array, count] = fscanf(fid,format,size)
</code></pre>
<p><br />
where the optional argument <code>size</code> specifies the amount of data to be read from the file. There are three versions of this argument,</p>
<ul>
<li><code>n</code>: Reads exactly <code>n</code> values. After this statement, <code>array</code> will be a column vector containing <code>n</code> values read from the file.</li>
<li><code>Inf</code>: Reads until the end of the file. After this statement, <code>array</code> will be a column vector containing all of the data until the end of the file.</li>
<li><code>[n m]</code>: Reads exactly, $n\times m$ values, and format the data as an $n\times m$ array. For example, consider <a href="http:/ICP2017F/lecture/11/nums2.txt" target="_blank">this file</a>, which contains two columns of numeric data. One could read this data using <code>fscanf()</code> like the following,
<pre><code class="language-matlab">>> formatSpec = '%d %f';
>> sizeA = [2 Inf];
>> fileID = fopen('nums2.txt','r');
>> A = transpose(fscanf(fileID,formatSpec,sizeA))
>> fclose(fileID);
A =
1.0000 2.0000 3.0000 4.0000 5.0000
0.8147 0.9058 0.1270 0.9134 0.6324
</code></pre>
<p><br />
Now suppose you perform some on operation on <code>A</code>, say the elemental multiplication of <code>A</code> by itself. Then you want to store (append) the result into another file. You can do this using MATLAB function <code>fprintf()</code>,</p>
<pre><code class="language-matlab">>> formatSpec = '%d %f \n';
>> fileID = fopen('nums3.txt','w+');
>> fprintf(fileID,formatSpec,A.*A);
>> fclose(fileID);
</code></pre>
<p><br />
The option <code>w+</code> tells MATLAB to store the result in a file named <a href="http:/ICP2017F/lecture/11/nums3.txt" target="_blank">num3.txt</a>, and if the file does already exist, then append the result to the end of the current existing file. To see what formatting specifiers you can use with MATLAB <code>fscanf()</code> and <code>fprintf()</code>, see <a href="https://www.mathworks.com/help/matlab/ref/fprintf.html" target="_blank">this page</a>.</p>
</li>
</ul>
<p>MATLAB also has some rules to skip characters that are unwanted in the text file. These rules are really details that are specific to your needs and the best approach is to seek the solution to your specific problem by searching MATLAB’s manual or the web. For example, consider <a href="http:/ICP2017F/lecture/11/temperature.dat" target="_blank">this file</a> which contains a set of temperature values in degrees (including the Celsius degrees symbol). One way to read this file and skipping the degrees symbol in MATLAB could be then the following set of commands,</p>
<pre><code class="language-matlab">>> fileID = fopen('temperature.dat','r');
>> degrees = char(176);
>> [A,count] = fscanf(fileID, ['%d' degrees 'C'])
>> fclose(fileID);
A =
78
72
64
66
49
count =
5
</code></pre>
<p><br />
This method of reading a file is very powerful but rather detailed, low-level and cumbersome, specially that you have to define the format for the content of the file appropriately. Most often, other higher-level MATLAB’s built-in function come to rescue us from the hassles of using <code>fscanf()</code>. For more information about this function though, if you really want to stick to it, see <a href="https://www.mathworks.com/help/matlab/ref/fscanf.html#buaio_v-5" target="_blank">here</a>. Some important MATLAB special characters (<strong>escape characters</strong>) that can also appear in <code>fprintf()</code> are also given in the following table.</p>
<table class="center">
<caption class="title" style="padding-bottom:10px;text-align:center;">
Table of escape characters in MATLAB.
</caption>
<thead>
<tr>
<th><font size="4rm" color="red">Symbol</font></th>
<th><font size="4rm" color="red">Effect on Text</font></th>
</tr>
</thead>
<tbody>
<tr><td><code>''</code></td><td>Single quotation mark</td></tr>
<tr><td><code>%%</code></td><td>Single percent sign</td></tr>
<tr><td><code>\\</code></td><td>Single backslash</td></tr>
<tr><td><code>\n</code></td><td>New line</td></tr>
<tr><td><code>\t</code></td><td>Horizontal tab</td></tr>
<tr><td><code>\v</code></td><td>Vertical tab</td></tr>
</tbody>
</table>
<p><br /></p>
<h4 id="readingwriting-data-using-dlmreaddlmwrite-and-csvreadcsvwrite">Reading/writing data using <code>dlmread()/dlmwrite()</code> and <code>csvread()/csvwrite()</code></h4>
<p>The methods discussed above are rather primitive, in that they require a bit of effort by the user to know something about the structure of the file and its format. MATLAB has a long list of advanced IO functions that can handle a wide variety of data file formats. Two of the most common functions are dedicated specifically to read data files containing delimited data sets: <code>csvread()</code> and <code>dlmread()</code>.</p>
<p>In the field of scientific computing, a <strong>Comma-Separated Values (CSV)</strong> data file is a type of file with extension <code>.csv</code>, which stores tabular data (numbers and text) in plain text format. Each line of the file is called a <strong>data record</strong> and each record consists of one or more <strong>fields, separated by commas</strong>. The use of the <strong>comma</strong> as a <strong>field separator</strong> is the source of the name for this file format.</p>
<p>Now suppose you wanted to read two matrices whose elements were stored in CSV format in two csv data files <a href="http:/ICP2017F/lecture/11/matrix1.csv" target="_blank">matrix1.csv</a> and <a href="http:/ICP2017F/lecture/11/matrix2.csv" target="_blank">matrix2.csv</a>. You can accomplish this task simply by calling MATLAB’s built-in csv-reader function called <code>csvread(filename)</code>. Here the word <code>filename</code> is the path to the file in your local hard drive. For example, download these two given csv files above in your MATLAB working directory and then try,</p>
<pre><code class="language-matlab">>> Mat1 = csvread('matrix1.csv');
>> Mat2 = csvread('matrix2.csv');
</code></pre>
<p><br />
Then suppose you want to multiply these two vectors and store the result in a new variable and write it to new output csv file. You could do,</p>
<pre><code class="language-matlab">Mat3 = Mat1 * Mat2;
>> csvwrite('matrix3.csv',Mat3)
</code></pre>
<p><br />
which would output <a href="http:/ICP2017F/lecture/11/matrix3.csv" target="_blank">this file: matrix3.csv</a> for you.</p>
<p>Alternatively, you could also use MATLAB’s built-in functions <code>dlmread()</code> and <code>dlmwrite()</code> functions to do the same things as above. These two functions read and write ASCII-delimited file of numeric data. For example,</p>
<pre><code class="language-matlab">>> Mat1 = dlmread('matrix1.csv');
>> Mat2 = dlmread('matrix2.csv');
>> Mat3 = Mat1 * Mat2;
>> dlmwrite('matrix3.dat',Mat3);
</code></pre>
<p><br />
Note that, <code>dlmread()</code> and <code>dlmwrite()</code> come with an optional argument <code>delimiter</code> of the following format,</p>
<pre><code class="language-matlab">>> dlmread(filename,delimiter)
>> dlmwrite(filename,matrixObject,delimiter)
</code></pre>
<p><br />
where the argument <code>delimiter</code> is the <strong>field delimiter character</strong>, specified as a character vector or string. For, example in the above case, the delimiter is comma <code>','</code>. In other cases, you could for example use white space <code>' '</code>, or <code>'\t'</code> to specify a tab delimiter, and so on. For example, you could have equally written,</p>
<pre><code class="language-matlab">>> dlmwrite('matrix4.dat',Mat3,'\t');
</code></pre>
<p><br />
to create a tab-delimited file named <a href="http:/ICP2017F/lecture/11/matrix4.csv" target="_blank">matrix4.dat</a>.</p>
<h4 id="readingwriting-data-using-xlsread-and-xlswrite">Reading/writing data using <code>xlsread()</code> and <code>xlswrite()</code></h4>
<p>Once data becomes more complex than simple numeric matrices or vectors, then we need more complex MATLAB functions for IO. An example of such case, is when you have stored your information in Microsoft Excel file. For such cases, you can use <code>xlsread(filename)</code> to read the file specified by the input argument <code>filename</code> to this function. We will later on see some example usages of this function in homework. Similarly, you could write data into an excel file using <code>xlswrite()</code>. For example,</p>
<pre><code class="language-matlab">>> values = {1, 2, 3 ; 4, 5, 'x' ; 7, 8, 9};
>> headers = {'First','Second','Third'};
>> xlswrite('XlsExample.xlsx',[headers; values]);
</code></pre>
<p><br />
would create this <a href="http:/ICP2017F/lecture/11/XlsExample.xlsx" target="_blank">Microsoft Excel file</a> for you.</p>
<h4 id="readingwriting-data-using-readtable-and-writetable">Reading/writing data using <code>readtable()</code> and <code>writetable()</code></h4>
<p>Another important and highly useful set of MATLAB functions for IO are <code>readtable()</code> and <code>writetable()</code>. The function <code>readtable()</code> is used to read data into MATLAB in the form of a MATLAB table data type. For example, you could read the same Excel file that we created above into MATLAB using <code>readtable()</code> instead of <code>xlsread()</code>,</p>
<pre><code class="language-matlab">>> XlsTable = readtable('XlsExample.xlsx')
XlsTable =
First Second Third
_____ ______ _____
1 2 '3'
4 5 'x'
7 8 '9'
</code></pre>
<p><br /></p>
<h4 id="reading-and-writing-image-files-using-imread-and-imwrite">Reading and writing image files using <code>imread()</code> and <code>imwrite()</code></h4>
<p>MATLAB has a really wide range of input/output methods of data. We have already discussed some of the most useful IO approaches in the previous sections. For graphics files however, none of the previous functions are useful. Suppose you wanted to import a <strong>jpg</strong> or <strong>png</strong> or some other type graphics file into MATLAB in order to further process it. For this purpose MATLAB has the built-in function <code>imread()</code> which can read image from an input graphics file. For example, to read <a href="http:/ICP2017F/lecture/11/homer.jpg" target="_blank">this image file</a> in MATLAB, you could do,</p>
<pre><code class="language-matlab">>> homer = imread('homer.jpg');
>> imshow(homer)
</code></pre>
<p><br />
to get the following figure in MATLAB,</p>
<figure>
<img src="http:/ICP2017F/lecture/11/homerScreenShot.png" width="900" />
</figure>
<p>Now suppose you want to convert this figure to black-and-white and save it as a new figure. You could do,</p>
<pre><code class="language-matlab">>> homerBW = rgb2gray(homer);
>> imshow(homerBW)
>> imwrite(homerBW,'homerBW.png');
</code></pre>
<p><br />
to get this <a href="http:/ICP2017F/lecture/11/homerBW.png" target="_blank">black and white version of the above image</a>, now in <strong>png</strong> format (or in any format you may wish, that is also supported by MATLAB).</p>
<h4 id="reading-a-file-using-importdata">Reading a file using <code>importdata()</code></h4>
<p>Probably, the most general MATLAB function for data input is <code>importdata()</code>. This function can be used to import almost any type of data and MATLAB is capable of automatically recognizing the correct format for reading the file, based on its extension and content. For example, you could read the same image file above, using <code>importdata()</code>,</p>
<pre><code class="language-matlab">>> newHomer = importdata('homer.jpg');
>> imshow(newHomer)
</code></pre>
<p><br />
to import it to MATLAB. At the same time, you could also use it to import data from the excel file that we created above, <a href="http:/ICP2017F/lecture/11/XlsExample.xlsx" target="_blank">XlsExample.xlsx</a>,</p>
<pre><code class="language-matlab">>> newXls = importdata('XlsExample.xlsx')
newXls =
data: [3x3 double]
textdata: {3x3 cell}
colheaders: {'First' 'Second' 'Third'}
</code></pre>
<p><br />
or similarly, read a csv-delimited file like <a href="http:/ICP2017F/lecture/11/matrix3.csv" target="_blank">matrix3.csv</a>,</p>
<pre><code class="language-matlab">>> newMat3 = importdata('matrix3.csv')
newMat3 =
Columns 1 through 7
62774 103230 77362 87168 65546 64837 100700
104090 143080 104700 116500 108250 105400 111110
80351 112850 89506 113890 106030 70235 110620
99522 134130 73169 134190 117710 92878 94532
59531 102750 91679 111350 80539 84693 96078
58504 76982 52076 91449 80797 69246 61569
76170 104310 93950 114860 89779 101530 87014
91610 118380 90636 107840 91120 90247 84871
85943 110670 73451 114410 100840 111660 77908
82570 94427 57213 81175 79305 78718 68662
Columns 8 through 10
79446 78102 106570
102950 116850 137810
113210 108800 128700
93013 119130 132700
95750 100980 100450
67044 80635 78006
86355 103760 119710
92649 98589 132660
73117 109270 99401
65283 66888 114030
</code></pre>
<p><br />
In general, you can use <code>importdata()</code> to read MATLAB binary files (MAT-files), ASCII files and Spreadsheets, as well as images and audio files.</p>
<h4 id="reading-a-file-using-fgetl">Reading a file using <code>fgetl()</code></h4>
<p>Another useful MATLAB function for reading the content of a file is <code>fgetl()</code> which can read a file line by line, removing the new line characters <code>\n</code> from the end of each line. The entire line is read as a string. For example, consider <a href="http:/ICP2017F/lecture/11/text.txt" target="_blank">this file</a>. One could read the content of this text file using the function <code>fgetl()</code> like the following,</p>
<pre><code class="language-matlab">>> fid = fopen('text.txt');
>> line = fgetl(fid) % read line excluding newline character
line =
The main benefit of using a weakly-typed language is the ability to do rapid prototyping. The number of lines of code required to declare and use a dynamically allocated array in C (and properly clean up after its use) are much greater than the number of lines required for the same process in MATLAB.
>> line = fgetl(fid) % read line excluding newline character
line =
''
>> line = fgetl(fid) % read line excluding newline character
line =
Weak typing is also good for code-reuse. You can code a scalar algorithm in MATLAB and with relatively little effort modify it to work on arrays as well as scalars. The fact that MATLAB is a scripted instead of a compiled language also contributes to rapid prototyping.
>> fclose(fid);
</code></pre>
<p><br /></p>
<h2 id="reading-data-from-web-using-webread">Reading data from web using <code>webread()</code></h2>
<p>In today’s world, it often happens that the data you need for your research is already stored somewhere on the world-wide-web. For such cases MATLAB has built-in methods and functions to read and import data or even a webpage. For example, consider <a href="https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/triggers.txt" target="_blank">this page</a> on this course’s website. It is indeed a text file containing a set of IDs for some astrophysical events. Suppose, you needed to read and store these IDs locally on your own device. You could simply try the following code in MATLAB to fetch all of the table’s information in a single string via,</p>
<pre><code class="language-matlab">>> webContent = webread('https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/triggers.txt')
webContent =
'00745966
00745090
00745022
00744791
00741528
00741220
00739517
00737438
...
00100319'
>>
</code></pre>
<p><br />
Now if we wanted to get the individual IDs, we could simply use <code>strplit()</code> function to split the IDs at the line break characters <code>'\n'</code>,</p>
<pre><code class="language-matlab">>> webContent = strsplit(webContent,'\n')
webContent =
1×1019 cell array
Columns 1 through 11
{'00745966'} {'00745090'} {'00745022'} ...
</code></pre>
<p><br /></p>
<p>We will see more sophisticated usages of this MATLAB function in the first problem of homework 5.</p>
<h2 id="handling-io-errors">Handling IO errors</h2>
<p>A good code has to be able to handle exceptional situations that may occur during the code execution. These exceptions may occur during data input from either command line, terminal window, or an input file. They may also occur as a result of repeated operations on the input data, inside the code. For example, in previous homework assignments, we have learned some simple ways of handling the wrong number of input arguments, for example in Fibonacci sequence problem. This and similar measures to handle nicely the unexpected runtime errors are collectively called <strong>error and exception handling</strong>.</p>
<p>A simple way of error handling is to write multiple if-blocks, each of which handles a special exceptional situation. That is, to let the code execute some statements, and if something goes wrong, write the program in such a way that can detect this and jump to a set of statements that handle the erroneous situation as desired.</p>
<p>A more modern and flexible way of handling such potential errors in MATLAB is through MATLAB’s <strong>try/catch</strong> construction. You can use a try/catch statement to execute code after your program encounters an error. try/catch statements can be useful when you Want to finish the program in another way that avoids errors (which could lead to abrupt interruption of the program), or when you want to nicely control the effects of error (for example, when a division by zero happens in your calculations), or you have a function that could take many problematic parameters or commands as input, just like the fib function we wrote in the previous homework assignments.</p>
<p>The general syntax for try/catch statements is like the following pseudocode,</p>
<pre><code class="language-matlab">try
try statements (all the normal things you would want to do)...
catch exception
catch block (things to do when the try statements go wrong) ...
end
</code></pre>
<p><br /></p>
<p>If an error occurs within the try block, MATLAB skips any remaining commands in the try block and executes the commands in the catch block. If no error occurs within try block, MATLAB skips the entire catch block.</p>
<p>For example, suppose we wanted to read data from a webpage that does not exist,</p>
<pre><code class="language-matlab">>> webContent = webread('https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/')
Error using readContentFromWebService (line 45)
The server returned the status 404 with message "Not Found" in response to the request to URL https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/.
Error in webread (line 125)
[varargout{1:nargout}] = readContentFromWebService(connection, options);
</code></pre>
<p><br />
In such cases, it would be nice to control the behavior of the problem, and not allow MATLAB to end the program abruptly. We could therefore say,</p>
<pre><code class="language-matlab">>> try
webContent = webread('https://www.shahmoradi.orghttp:/ICP2017F/homework/5-problems/')
catch
disp('The requested page does not exist! Gracefully exiting...')
end
The requested page does not exist! Gracefully exiting...
</code></pre>
<p><br />
Now, the true advantage of this error handling construct would become clear to you when you use it in functions. We will see more of this in homework 5.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/lecture/11-matlab-IO">Lecture 11: MATLAB - Input/Output (IO)</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on November 08, 2017.</p><![CDATA[Homework 4: Problems - loops, IO]]>http:/ICP2017F/homework/4-problems-loops-IO2017-10-30T00:00:00-05:002017-10-30T00:00:00-05:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>♣ <strong>Due Date: Monday Nov 13, 2017 9:00 AM</strong>. This homework aims at giving you some experience with MATLAB for-loops and while-loops as well as input/output functionalities in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> <strong>The while-loop implementation of a for-loop.</strong> Consider the following two vectors of temperatures in Celsius degrees to Fahrenheit.</p>
<pre><code class="language-matlab">Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]
Fdegrees = [-20, -15, -5, 0, 10, 15, 30, 35, 40]
</code></pre>
<p><br />
Our goal in this problem is to write functions that take such vectors as input and perform some actions on them. The functions take as input, a vector of temperatures just like <code>Cdegrees</code> and <code>Fdegrees</code> above, as well as an input string which is either <code>'F2C'</code> or <code>C2F</code>. Then, converts the input temperature vector from Fahrenheit to Celsius if the input string is <code>'F2C'</code>, otherwise converts the input temperature vector from Celsius to Fahrenheit if the input string is <code>'C2F'</code>, otherwise outputs an error message and aborts the program.</p>
<p>(A) Write the requested function using while-loop construct (you can name the function <code>convertTempFor.m</code>).<br />
(B) Write the requested function using for-loop construct (you can name the function <code>convertTempWhile.m</code>).<br />
(C) Write the requested function using vectorization concept (you can name the function <code>convertTempVec.m</code>).</p>
<p>Here are some example calls to these functions,</p>
<pre><code class="language-matlab">InVec = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40];
>> convertTempFor(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
>> convertTempWhile(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
>> convertTempVec(InVec,'C2F')
ans =
-4 5 14 23 32 41 50 59 68 77 86 95 104
</code></pre>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>2. </strong> Use MATLAB built-in timing functions to measure the performance of three functions you wrote in question 1 above.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>3. </strong> Consider the following nested cell vector,</p>
<pre><code class="language-matlab">List = { {'M','A','T','L','A','B'}, {' '}, {'i','s'}, {' '}, {'a'}, {' '}, {'s','t','r','a','n','g','e'}, {', '}, {'b','u','t',' '}, {'p','o','p','u','l','a','r'}, {' '}, {'p','r','o','g','r','a','m','m','i','n','g',' ','l','a','n','g','u','a','g','e'} };
</code></pre>
<p><br />
Write a MATLAB script <code>extractLetter.m</code> that uses for-loop to extract all the letters in the variable list and finally prints them all as a single string like the following,</p>
<pre><code class="language-matlab">>> extractLetter
MATLAB is a strange, but popular programming language
</code></pre>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>4. </strong> <strong>The significant impact of round-off errors in numerical computation.</strong> Consider the following program,</p>
<pre><code class="language-matlab">formatSpec = 'With %d sqrt, then %d times ^2 operations, the number %.16f becomes: %.16f \n'; % the string format for fprintf function
for n = 1:60
r_original = 2.0;
r = r_original;
for i = 1:n
r = sqrt(r);
end
for i = 1:n
r = r^2;
end
fprintf(formatSpec,n,n,r_original,r);
end
</code></pre>
<p><br />
Explain what this code does. Then run the code, and explain why do you see the behavior observed. In particular, why do you not recover the original value $2.0$ after many repetitions of the same forward and reverse task of taking square root and squaring the result?</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>5. </strong> Consider the following code,</p>
<pre><code class="language-matlab">eps = 1.0;
while 1.0 ~= 1.0 + eps
disp(num2str(eps));
eps = eps / 2.0;
end
disp(['final eps:', num2str(eps)]);
</code></pre>
<p><br /><br />
Explain what the code is doing. Run the code and observe the output. How could <code>1.0 ~= 1.0 + eps</code> be <code>false</code>?!</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>6. </strong> Suppose you want to find the largest prime number that is smaller than a given input value by the user. Write a function named <code>getLargestPrime</code> that does so, using for-loop, break, and MATLAB’s intrinsic function isprime(). Here is a test,</p>
<pre><code class="language-matlab">>> getLargestPrime(123)
ans =
113
</code></pre>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>7. </strong> Consider the problem number 5 in HW 3, where we wrote a <a href="http:/ICP2017F/homework/3-solutions/fib.m">function</a> named <code>fib.m</code> that used the idea of recursive functions to generate the Fibonacci numbers.</p>
<p>(A) Download <a href="http:/ICP2017F/homework/3-solutions/fib.m" target="_blank">this function fib()</a> and modify it using MATLAB <code>timeit()</code> function such that it also returns the average runtime of <code>getFib()</code> nested function inside <code>fib()</code>, right after giving the requested Fibonacci number. For example, here is an output from such modified code:</p>
<pre><code class="language-matlab">>> fib
Please enter a non-negative integer or type stop: 10
fib(10) = 55
average runtime: 1.0083e-05 seconds
Please enter a non-negative integer or type stop: 15
fib(15) = 610
average runtime: 8.8884e-05 seconds
Please enter a non-negative integer or type stop: 20
fib(20) = 6765
average runtime: 0.00095559 seconds
Please enter a non-negative integer or type stop: 25
fib(25) = 75025
average runtime: 0.010311 seconds
Please enter a non-negative integer or type stop: 30
fib(30) = 832040
average runtime: 0.11575 seconds
Please enter a non-negative integer or type stop: 35
fib(35) = 9227465
average runtime: 1.2904 seconds
Please enter a non-negative integer or type stop: stop
</code></pre>
<p><br />
(Note that you can use <code>char(9)</code> at the beginning of your <code>disp()</code> messages in order to add the <code>tab</code> character at the beginning of your message, just like the above example.)</p>
<p>(B) Now copy this function to a new MATLAB M-file named <code>fibLoop.m</code>. Also modify the name of the function <code>fib()</code> in this file <code>fibLoop()</code>. Modify the nested function <code>getFib()</code> inside of <code>fibLoop()</code> such that instead of recursive function calls, it uses a for-loop to find the requested Fibonacci number.</p>
<p>(C) Now time your new function <code>fibLoop()</code> for the same input integers as in the above example: $10,15,20,25,30,35$. How do the runtimes for <code>fibLoop()</code> compare with <code>fib()</code>. Which function is faster and more efficient: <code>fib()</code> or <code>fibLoop()</code>? Why is there such huge difference in the performance of the two functions?</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>8. </strong> <strong>(A)</strong> Write two new MATLAB functions <code>timeFib(n)</code> and <code>timeFibLoop(n)</code> based on your MATLAB functions <code>fib()</code> and <code>fibLoop()</code> that you wrote in problem 6, such that both take an integer and output a structure whose fields are:</p>
<pre><code class="language-matlab">output.n
output.fib
output.runtime
</code></pre>
<p><br />
Note that the function should take as input only an integer variable, so you need to modify your old codes to only check whether the input <code>~ischar()</code>, and <code>isreal()</code> and <code>n>=0</code> and <code>round(n)==n</code>. Here is an example output from the two functions,</p>
<pre><code class="language-matlab">>> timeFib(20)
ans =
n: 20
fib: 6765
runtime: 9.6568e-04
>> timeFib('amir')
Error using timeFib (line 8)
The input argument is not a non-negative integer!
>> timeFibLoop(20)
ans =
n: 20
fib: 6765
runtime: 4.4076e-06
>> timeFibLoop('amir')
Error using timeFibLoop (line 8)
The input argument is not a non-negative integer!
</code></pre>
<p><br />
<strong>(B)</strong> Now write a script named <code>writeFibResult.m</code> that calls these two functions for a range of input $n={10,2,3,\ldots,35}$ values, and then write the output of these two functions in a formatted way in two files like these <a href="http:/ICP2017F/homework/4-problems/fibOutput.txt" target="_blank">fibOutput.txt</a> and <a href="http:/ICP2017F/homework/4-problems/fibLoopOutput.txt" target="_blank">fibLoopOutput.txt</a>. You can use any of MATLAB IO methods to create the output file with any file extension you prefer: <code>.txt</code>, <code>.csv</code>, <code>.xlsx</code>, <code>.tab</code>, … .</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/4-problems-loops-IO">Homework 4: Problems - loops, IO</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on October 30, 2017.</p><![CDATA[Homework 3: Solutions - structures, branching and functions in MATLAB]]>http:/ICP2017F/homework/3-solutions-matlab-structures-branching-functions2017-10-30T00:00:00-05:002017-10-30T00:00:00-05:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="3-problems-matlab-structures-branching-functions.html" target="_blank">Homework 3: Problems - structures, branching and functions in MATLAB</a>.</p>
<p>The following figure illustrates the grade distribution for this homework.</p>
<figure>
<img src="http:/ICP2017F/homework/gradeDist/gradeHistHomework3.png" width="700" />
<figcaption style="text-align:center">
Maximum possible points, excluding bonus question, is 100.
</figcaption>
</figure>
<hr />
<hr />
<p><br /></p>
<p>♣ <strong>Due Date: Monday Oct 30, 2017 9:00 AM</strong>. This homework aims at giving you some experience with structure types in MATLAB as well as branching and function concepts and their usage syntax. Write your MATLAB scripts with the corresponding <code>*.m</code> file names, and add a readme.md file in HW 3 folder of your ICP2017F repository if you need to add any additional explanation (Don’t forget to use markdown syntax highlight in your readme file, if needed).</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> The bell-shaped <a href="https://en.wikipedia.org/wiki/Normal_distribution" target="_blank">Gaussian probability density function</a>,</p>
<script type="math/tex; mode=display">f(x)=\frac{1}{\sqrt{2\pi}\sigma}\exp\bigg[ -\frac{1}{2}\bigg( \frac{x-\mu}{\sigma} \bigg)^2 \bigg]</script>
<p><br />
is one of the most widely used functions in science and technology. The parameters of the function ($\mu\in[-\infty,+\infty]$, $\sigma>0$) are prescribed real numbers. Write a MATLAB script for evaluating this function when $\mu=0$, $\sigma=2$, $x = 1$.</p>
<p><br />
Verify your answer by getting the same result from <a href="https://www.wolframalpha.com/" target="_blank">Wolfram Alpha</a> mathematical search engine, also by using MATLAB’s builtin function <a href="https://www.mathworks.com/help/stats/normpdf.html" target="_blank">normpdf($x$,$\mu$,$\sigma$)</a>.</p>
<p><strong>Answer:</strong></p>
<p>An example implementation can be found <a href="http:/ICP2017F/homework/3-solutions/getNormPDF.m" target="_blank">here</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>2. </strong> As an egg cooks, the protein molecules in the egg first denature and then coagulate. When the temperature exceeds a critical point, reactions begin and proceed faster as the temperature increases. In the egg white, the proteins start to coagulate for temperatures above $63^\circ\rm{C}$, while in the yolk the proteins start to coagulate for temperatures above $70^\circ\rm{C}$. For a soft boiled egg, the white needs to have been heated long enough to coagulate at a temperature above $63^\circ\rm{C}$, but the yolk should not be heated above $70^\circ\rm{C}$. For a hard boiled egg, the center of the yolk should be allowed to reach $70^\circ\rm{C}$.</p>
<p>The following formula expresses the time $t$ it takes (in seconds) for the center of the yolk to reach the temperature Ty (in Celsius degrees):</p>
<script type="math/tex; mode=display">t = \frac
{ M^{2/3} ~ c ~ \rho^{1/3} }
{ K\pi^2 ~ (4\pi/3)^{2/3} }
~\ln
\bigg[
0.76 \frac{T_0 - T_w}{T_y-T_w}
\bigg]</script>
<p><br />
where $M$ is the mass of egg, $\rho$ is the density, $c$ is the specific heat capacity, and $K$ is thermal conductivity. Relevant values are $M=47~[g]$ for a small egg and $M=67~[g]$ for a large egg, $\rho=1.038 ~[g~cm^{-3}]$, $c = 3.7 ~[J~g^{-1}~K^{-1}]$, and $K = 5.4\times10^{-3} ~[Wcm^{-1}K^{-1}]$. Furthermore, $T_w$ is the temperature
(in C degrees) of the boiling water, and $T_0$ is the original temperature (in C degrees) of the egg before being put in the water. Implement the formula in a MATLAB program, set $T_w = 100^\circ C$ and $T_y = 70^\circ C$, and compute $t$ for a large egg taken from the fridge ($T_0 = 4^\circ C$) and from room temperature ($T_0 = 20^\circ C$). (<strong>Hint</strong>: Note that for this problem you will need to use MATLAB’s builtin function <code>log()</code>, and the predefined variable <code>pi</code>.)</p>
<p><strong>Answer:</strong></p>
<p>An example implementation can be found <a href="http:/ICP2017F/homework/3-solutions/protein.m" target="_blank">here</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>3. </strong> <strong>Converting polar and Cartesian vector representations using functions and structures.</strong> A vector is a mathematical quantity that has both magnitude and direction. A 2-dimensional vector can be represented as a displacement along $x$ and $y$ axes in rectangular (Cartesian) coordinates or, by a distance $r$ and an angle $\phi$ in polar coordinates,</p>
<figure>
<img src="http:/ICP2017F/homework/3-problems/vector.png" height="400" width="400" />
<figcaption style="text-align:center">
The conversion rule between the Cartesian and Polar representations of a vector.
</figcaption>
</figure>
<p>The relationships between the Cartesian $(x,y)$ and polar $(r,\phi)$ coordinates are given by the following equations,</p>
<script type="math/tex; mode=display">% <![CDATA[
\begin{align*}
x &= r\cos(\phi) \\
y &= r\sin(\phi) \\
r &= \sqrt{x^2 + y^2} \\
\end{align*} %]]></script>
<p>Write a MATLAB function <code>getPolar(inputCartesianStruct)</code> that takes a structure <code>inputCartesianStruct</code> as input, that has two components <code>x</code> and <code>y</code>. Then on output, it returns another structure that has to components <code>r</code> and <code>phi</code>. Write another function <code>getCart(inputPolarStruct)</code> that does the inverse of <code>getPolar(inputCartesianStruct)</code>. Make sure that both functions are robust to wrong input structures by checking whether the input structures have the required fields: <code>x</code> and <code>y</code>, or <code>r</code> and <code>phi</code>. You can do so by using MATLAB’s builtin function <code>isfield()</code>.</p>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of <a href="http:/ICP2017F/homework/3-solutions/getPolar.m" target="_blank">getPolar.m</a> and <a href="http:/ICP2017F/homework/3-solutions/getCart.m" target="_blank">getCart.m</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>4. </strong> <strong>Calculating the size of a directory</strong> The MATLAB function <code>dir</code> returns the contents of a specified directory. It returns the result in the form of an structure array with four fields, for example,</p>
<pre><code class="language-matlab">>> s = dir
s =
123x1 struct array with fields:
name
date
bytes
isdir
datenum
>> size(s)
ans =
123 1
>> fieldnames(s)
ans =
'name'
'date'
'bytes'
'isdir'
'datenum'
</code></pre>
<p><br />
where here, the directory contains 123 objects. Write a MATLAB function that takes the path to a directory and outputs the total size of all files in the directory in units of bytes.</p>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of <a href="http:/ICP2017F/homework/3-solutions/getBytes.m" target="_blank">getBytes.m</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>5. </strong> In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, that are characterized by the fact that every number after the first two is the sum of the two preceding ones:</p>
<script type="math/tex; mode=display">0,~1,~1,~2,~3,~5,~8,~13,~21,~34,~55,~89,~144,~\dots</script>
<p>with the following sequence equation,</p>
<script type="math/tex; mode=display">% <![CDATA[
\begin{eqnarray}
Fib(n) &=& Fib(n-1) + Fib(n-2) ~, \\
Fib(0) &=& 0 ~, \\
Fib(1) &=& 1 ~.
\end{eqnarray} %]]></script>
<p>Write a MATLAB function named <code>fib</code> that takes in an input argument which should be integer number <code>n</code>, and then calculates the $n$th number in the Fibonacci sequence and outputs it on the screen. Also, if the input argument is not a non-negative integer, it prints an error message on the screen and asks the user to re-enter a non-negative integer number. Also, when it is done with finding the requested Fibonacci number, it asks again the user to either input a new non-negative integer, or enter ‘stop’ to end the function, like the following,</p>
<pre><code class="language-matlab">>> fib
Please enter a non-negative integer or type stop: -123
The input argument is not a non-negative integer!
Please enter a non-negative integer or type stop: a
The input argument is not a non-negative integer!
Please enter a non-negative integer or type stop: amir
The input argument is not a non-negative integer!
Please enter a non-negative integer or type stop:
The input argument is not a non-negative integer!
Please enter a non-negative integer or type stop: -12.3
The input argument is not a non-negative integer!
Please enter a non-negative integer or type stop: 0
fib(0) = 0
Please enter a non-negative integer or type stop: 1
fib(1) = 1
Please enter a non-negative integer or type stop: 2
fib(2) = 1
Please enter a non-negative integer or type stop: 3
fib(3) = 2
Please enter a non-negative integer or type stop: 4
fib(4) = 3
Please enter a non-negative integer or type stop: 5
fib(5) = 5
Please enter a non-negative integer or type stop: 6
fib(6) = 8
Please enter a non-negative integer or type stop: 7
fib(7) = 13
Please enter a non-negative integer or type stop: 8
fib(8) = 21
Please enter a non-negative integer or type stop: 9
fib(9) = 34
Please enter a non-negative integer or type stop: 10
fib(10) = 55
Please enter a non-negative integer or type stop: 11
fib(11) = 89
Please enter a non-negative integer or type stop: 12
fib(12) = 144
Please enter a non-negative integer or type stop: 22
fib(22) = 17711
Please enter a non-negative integer or type stop: 32
fib(32) = 2178309
Please enter a non-negative integer or type stop: stop
>>
</code></pre>
<p><br /></p>
<p><strong>Hint:</strong></p>
<ol>
<li>First write a function <code>getFib(n_int)</code> that finds the requested Fibonacci number for you, given a <em>strictly</em> non-negative integer input (for example, name it <code>n_int</code>).<br />
<br /></li>
<li>Then put this function <strong>inside another MATLAB function <code>fib()</code></strong> that asks the user to input a number (which could be potentially anything: a string, a real number, a complex number, or an integer). You can do this using MATLAB’s builtin function <code>input()</code>. Read the input value as a <code>string</code> using this MATLAB function. Then check if the user’s input string is equivalent to <strong>‘stop’</strong> or not. If it is ‘stop’, then the program must return, otherwise, use <code>str2double()</code> to convert this string to MATLAB numeric type. Then check is the numeric-converted input value is real number (as opposed to complex number) via MATLAB’s function <code>isreal()</code>. If the value is real, then check if it is a non-negative real number. Also check if it is an <strong>integer</strong> by comparing the value with its rounded value using MATLAB’s function <code>round()</code>. Thus is the user-input number is really a non-negative integer, then your code should display the result message as given in the above output (by calling your nested function <code>getFib(n_int)</code>), and then call this function <code>fib</code> to ask the user to input another number again, to repeat this procedure. If the user-input number is not a non-negative integer, then your code should display the requested message above, and call the function <code>fib</code> again to ask the user for another input.</li>
</ol>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of <a href="http:/ICP2017F/homework/3-solutions/fib.m" target="_blank">fib.m</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>6. </strong> An arbitrary triangle can be described by the coordinates of its three vertices: $(x1,y1),(x2,y2),(x3,y3)$, numbered in a counterclockwise direction. The area of the triangle is given by the formula,</p>
<script type="math/tex; mode=display">A = \frac{1}{2} \bigg| x2y3 - x3y2 - x1y3 + x3y1 + x1y2 - x2y1 \bigg|</script>
<p>Write a function <code>getTriangleArea(vertices)</code> that returns the area of a triangle whose vertices are specified by the argument vertices, which is a nested list of the vertex coordinates.</p>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of <a href="http:/ICP2017F/homework/3-solutions/getTriangleArea.m" target="_blank">getTriangleArea.m</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>7. </strong> Write a logical (boolean) function named <code>isPrime(n)</code> that takes in an integer number <code>n</code>, and finds whether it is a <a href="https://en.wikipedia.org/wiki/Prime_number" target="_blank">Prime number</a> or not. Example output is the following,</p>
<pre><code class="language-matlab">isPrime(23)
</code></pre>
<pre><code>True
</code></pre>
<pre><code class="language-matlab">isPrime(12)
</code></pre>
<pre><code>False
</code></pre>
<p>Note that you do not need and don’t have to use a <code>for-loop</code> for this problem (we have not yet discussed loops in our class!). All of it can be done using <strong>recursive function</strong> concept. You can verify the accuracy of your MATLAB script via by checking its output against MATLAB’s builtin function <code>isprime()</code>.</p>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of <a href="http:/ICP2017F/homework/3-solutions/isPrime.m" target="_blank">isPrime.m</a>.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>8. </strong> <strong>Function generators.</strong> Write a nested function that evaluates a polynomial of the form $y = ax^2+bx+c$. The host function <code>genFunc()</code> should be able to take varying number of arguments using <code>varargin</code> with maximum of 3 arguments (<code>a,b,c</code>) to initialize the coefficients of the polynomial. If there is only one argument, then <code>b</code> and <code>c</code> must be set to zero. If there are two input arguments, then <code>c</code> is set to zero. If none are given on input, then the returned function should be zero. If more than 3 arguments exist, then the function should display an error and stop. Also, if the input arguments are not real numbers, then the function should return and error and stop.</p>
<p>On output, the host function should create and return a function handle for the nested function <code>evalFunc()</code>. The nested function should calculate a value of $y$ for a given value of $x$, using the values of $a$, $b$, and $c$ stored in the host function. This is called a <strong>function generator</strong>, since the host function generates and outputs another function that can be called and used later on in the program. Once you create your function generator, test it in the following way: Call <code>genFunc(1,2,0)</code> and save the output function handle in a variable, say <code>h1</code>. Call <code>genFunc(1,2)</code> and save the output function handle in a variable, say <code>h2</code>. Then these two function handles, should give the same result, given the same input <code>x</code> values.</p>
<p><strong>Answer:</strong></p>
<p>Here is an example implementation of <a href="http:/ICP2017F/homework/3-solutions/genFunc.m" target="_blank">genFunc.m</a>.</p>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/homework/3-solutions-matlab-structures-branching-functions">Homework 3: Solutions - structures, branching and functions in MATLAB</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on October 30, 2017.</p><![CDATA[Lecture 10: MATLAB - loops and vectorization]]>http:/ICP2017F/lecture/10-matlab-loops-vectorization2017-10-27T00:00:00-05:002017-10-27T00:00:00-05:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This lecture explains the concept of for-loops and while-loops in MATLAB and different of types of it in MATLAB.</p>
<div class="post_toc"></div>
<h2 id="lecture-videos">Lecture Videos</h2>
<p>This video is created solely as reference for the attendants of ICP2017F course at UT Austin. If you did not attend this class, then you may not find this video useful.</p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/GvIYiE59YgE" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/h2sYfv4DRd8" frameborder="0" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/kNH9iZAI9CU" frameborder="0" gesture="media" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<div class="center"><div class="video-wrapper"><div class="video-container">
<iframe width="853" height="480" src="https://www.youtube.com/embed/jed9DCFzXTc" frameborder="0" gesture="media" allowfullscreen=""></iframe>
</div></div></div>
<p><br /></p>
<h2 id="loops-in-matlab">Loops in MATLAB</h2>
<p>Many programming algorithms require iteration, that is, the repetitive execution of a block of program statements. Similar to other programming languages, MATLAB also has built-in tools for iterative tasks in codes.</p>
<h3 id="for-loop">For-loop</h3>
<p>The for-loop is among the most useful MATLAB constructs. The general syntax of for-loop is,</p>
<pre><code class="language-matlab">for variable = expression
statements
end
</code></pre>
<p><br />
Usually, <code>expression</code> is a vector of the form <code>istart:stepSize:iend</code> where <code>fix((iend-istart)/stepSize+1)</code> gives the number of iterations requested by the user, assuming <code>iend>istart</code>. The <code>statements</code> are the set of programming tasks that have to be repeated. For example consider a script named <code>forLoop.m</code>,</p>
<pre><code class="language-matlab">for index = istart:stepSize:iend
disp(index);
end
disp( [ 'number of iterations: ', num2str( fix((iend-istart)/stepSize+1) ) ] );
</code></pre>
<pre><code class="language-matlab">>> istart = -2;
iend = 10;
stepSize = 3;
forLoop
-2
1
4
7
10
number of iterations: 5
</code></pre>
<p><br />
You can also iterate in reverse order,</p>
<pre><code class="language-matlab">>> istart = 10;
iend = -2;
stepSize = -3;
forLoop
10
7
4
1
-2
number of iterations: 5
</code></pre>
<p><br /></p>
<h4 id="breaking-a-for-loop-immaturely">Breaking a for-loop immaturely</h4>
<p>You can also use <code>break</code> inside a for-loop to get out of it, even before the for-loop finishes the full number of iterations. This is specially useful when you want to ensure if a condition has happened, and if so, then terminate the for-loop. For example,</p>
<pre><code class="language-matlab">for integer = 1:10
disp(integer)
if (integer==5)
break
end
end
</code></pre>
<pre><code> 1
2
3
4
5
</code></pre>
<p><strong>Exercise:</strong><br />
suppose you want to find the largest prime number that is smaller than a given input value by the user. Write a function that does so, using for-loop, <code>break</code>, and MATLAB’s intrinsic function <code>isprime()</code>.</p>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">function integer = getPrime(upper)
if (upper<1)
disp('input value cannot be less than 1. Goodbye!')
return
end
for integer = upper:-1:1
if isprime(integer)
break
end
end
end
</code></pre>
<p><br /></p>
<h4 id="continue-statement-within-for-loops">Continue statement within for-loops</h4>
<p>To skip the rest of the instructions in a loop and begin the next iteration, you can use a <code>continue</code> statement. For example, the following code prints only integers that are primes,</p>
<pre><code class="language-matlab">for integer = 1:10
if ~isprime(integer)
continue
end
disp(['prime detected! ',num2str(integer)])
end
</code></pre>
<pre><code>prime detected! 2
prime detected! 3
prime detected! 5
prime detected! 7
</code></pre>
<h4 id="iterating-over-vectors-matrices-and-cell-using-for-loops">Iterating over vectors, matrices, and cell using for-loops</h4>
<p>Note that the index of for-loop must not necessarily be an integer. Basically you can use the for-loop index to iterate over anything that is iterable in MATLAB. For example, consider the following,</p>
<pre><code class="language-matlab">a = [1,0,2,3,7,-1];
for index = a
disp(class(index))
disp(index)
end
</code></pre>
<p><br />
The output of this script is,</p>
<pre><code>double
1
double
0
double
2
double
3
double
7
double
-1
</code></pre>
<p>But, see what happens if we defined <code>a</code> as a matrix,</p>
<pre><code class="language-matlab">a = [1, 2, 3; 4, 5, 6; 7, 8, 9];
for index = a
disp(class(index))
disp(index)
end
</code></pre>
<pre><code>double
1
4
7
double
2
5
8
double
3
6
9
</code></pre>
<p>What is happening here? The answer is that, MATLAB is a <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order" target="_blank">column-wise programming language</a>, just like Fortran, and unlike C, C++ and all of their descendants. <strong>MATLAB, by default, iterates over elements of row vectors</strong>. Therefore, when you use a matrix as the iterator in for-loops, MATLAB considers an entire column as the index of for-loop. The same is also true for other multidimensional arrays in MATLAB, for example cell arrays,</p>
<pre><code class="language-matlab">a = {1, 2, 3; 4, 5, 6; 7, 8, 9};
for index = a
disp(class(index))
disp(index)
end
</code></pre>
<pre><code>cell
[1]
[4]
[7]
cell
[2]
[5]
[8]
cell
[3]
[6]
[9]
</code></pre>
<p>Therefore, if you want to iterate over elements of a multidimensional matrix or array, you have to first reshape them using MATLAB’s built-in <code>reshape()</code> function to convert them to vector format, then iterating over them. For exzmple,</p>
<pre><code class="language-matlab">a = {1, 2, 3; 4, 5, 6; 7, 8, 9};
a = reshape(a,[1,9]);
for index = a
disp(class(index))
disp(index)
end
</code></pre>
<pre><code>cell
[1]
cell
[4]
cell
[7]
cell
[2]
cell
[5]
cell
[8]
cell
[3]
cell
[6]
cell
[9]
</code></pre>
<h4 id="some-general-advice-on-for-loop-index">Some general advice on for-loop index</h4>
<ul>
<li><strong>Avoid using $i$ and $j$ as index variables in for-loops.</strong> Note that <code>i</code> and <code>j</code> have special meanings in MATLAB, as described in previous lectures. They are used to define complex numbers. Using these variable names as indices in MATLAB for-loops, would overwrite the default meaning of these variables.<br />
<br /></li>
<li><strong>Avoid assigning a value to the index variable within the loop statements.</strong> The for statement overrides any changes made to index within the loop.</li>
</ul>
<h3 id="while-loop">While-loop</h3>
<p>There is another iteration construct in MATLAB, called <strong>while-loop</strong> which has the following general syntax,</p>
<pre><code class="language-matlab">while expression
statements
end
</code></pre>
<p><br />
The <code>statements</code> within the while-loop are executed as long as <code>expression</code> is true. For example,</p>
<pre><code class="language-matlab">x = realmax();
while x>0
xmin = x
x = log(x)
end
xmin
</code></pre>
<pre><code>xmin =
1.7977e+308
x =
709.7827
xmin =
709.7827
x =
6.5650
xmin =
6.5650
x =
1.8817
xmin =
1.8817
x =
0.6322
xmin =
0.6322
x =
-0.4585
xmin =
0.6322
</code></pre>
<p>Note that, <code>break</code> and <code>continue</code> can be used in while-loops in the same fashion as they are used in for-loops, described above. The condition is evaluated before the body is executed, so it is possible to get zero iterations. It’s often a good idea to limit the number of repetitions to avoid infinite loops (as could happen above if x is infinite). This can be done in a number of ways, but the most common is to use <code>break</code>. For example,</p>
<pre><code class="language-matlab">n = 0;
while abs(x) > 1
x = x/2;
n = n+1;
if n > 50, break, end
end
</code></pre>
<p><br />
A break immediately jumps execution to the first statement after the loop. It’s good practice to include some diagnostic output or other indication that an abnormal loop exit has occurred once the code reach the <code>break</code> statement.</p>
<p><strong>Exercise:</strong><br />
Write function <code>getFac(n)</code> using while-loop, that calculates the factorial of an input number <code>n</code>. For example,</p>
<pre><code class="language-matlab">>> getFac(4)
4! = 24
</code></pre>
<p><br /></p>
<!--
**Answer:**
```matlab
function getFac(n)
nOrg = n;
fac = n;
while n > 1
n = n-1;
fac = fac*n;
end
disp([num2str(nOrg),'! = ' num2str(fac)])
end
```
<br>
-->
<h4 id="some-general-advice-on-while-loops">Some general advice on while-loops</h4>
<ul>
<li>If you inadvertently create an infinite loop (that is, a loop that never ends on its own), stop execution of the loop by pressing Ctrl+C.<br />
<br /></li>
<li>If the conditional expression evaluates to a matrix, MATLAB evaluates the statements only if <strong>all</strong> elements in the matrix are true (nonzero). To execute statements if any element is true, wrap the expression in the <code>any()</code> function.<br />
<br /></li>
<li>To exit the loop, use a <code>break</code> statement as discussed above. To skip the rest of the instructions in the loop and begin the next iteration, use a <code>continue</code> statement.<br />
<br /></li>
<li>When nesting a number of while statements, each while statement requires an <code>end</code> keyword.</li>
</ul>
<h2 id="vectorization-in-matlab">Vectorization in MATLAB</h2>
<p>Experienced programmers who are concerned with producing compact and fast code try to avoid for loops wherever possible in their MATLAB codes. There is a reason for this: for-loops and while-loops have significant overhead in interpreted languages such as MATLAB and Python.</p>
<p>There is of course, a remedy for this inefficiency. Since MATLAB is a matrix language, many of the matrix-level operations and functions are carried out internally using compiled C, Fortran, or assembly codes and are therefore executed at near-optimum efficiency. This is true of the arithmetic operators <code>*</code>, <code>+</code>,<code>-</code>,<code>\</code>, <code>/</code> and of relational and logical operators. However, for loops may be executed
relatively slowly—depending on what is inside the loop, MATLAB may or may not
be able to optimize the loop. One of the most important tips for producing efficient M-files is to avoid for -loops in favor of vectorized constructs, that is, to convert for-loops into equivalent vector or matrix operations. Vectorization has important benefits beyond simply increasing speed of execution. It can lead to shorter and more readable MATLAB code. Furthermore, it expresses algorithms in terms of high-level constructs that are more appropriate for high-performance computing. For example, consider the process of summation of a random vector in MATLAB,</p>
<pre><code class="language-matlab">>> n = 5e7; x = randn(n,1);
>> tic, s = 0; for i=1:n, s = s + x(i)^2; end, toc
</code></pre>
<pre><code>Elapsed time is 0.581945 seconds.
</code></pre>
<p>Now doing the same thing, using array notation would yield,</p>
<pre><code class="language-matlab">>> tic, s = sum(x.^2); toc
</code></pre>
<pre><code>Elapsed time is 0.200450 seconds.
</code></pre>
<p>Amazing! isn’t it? You get almost 3x speedup in your MATLAB code if you use vectorized computation instead of fol-loops. Later on in this course, we will see that MATLAB has inherited these excellent vectorization techniques and syntax for matrix calculations from its high-performance ancestor, <a href="https://en.wikipedia.org/wiki/Fortran" target="_blank">Fortran</a>.</p>
<p><strong>Exercise:</strong><br />
How do you vectorize the following code?</p>
<pre><code class="language-matlab">i = 0;
for t = 0:.01:10
i = i + 1;
y(i) = sin(t);
end
</code></pre>
<p><br /></p>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">t = 0:.01:10;
y = sin(t);
</code></pre>
<p><br /></p>
<h3 id="vectorization-of-array-operations">Vectorization of array operations</h3>
<p>Vectorization of arrays can be done through <strong>array operators</strong>, which perform the same operation for all elements in the data set. These types of operations are useful for repetitive calculations. For example, suppose you collect the volume (V) of various cones by recording their diameter (D) and height (H). If you collect the information for just one cone, you can calculate the volume for that single cone as,</p>
<pre><code class="language-matlab">>> D = 0.2;
>> H = 0.04;
>> V = 1/12*pi*(D^2)*H
V =
4.1888e-04
</code></pre>
<p><br />
Now, suppose we collect information on 10,000 cones. The vectors <code>D</code> and <code>H</code> each contain 10,000 elements, and you want to calculate 10,000 volumes. In most programming languages (except Fortran and R which have similar vectorization capabilities to MATLAB), you need to set up a loop similar to this MATLAB code (here instead of 10000, I am using 7):</p>
<pre><code class="language-matlab">>> D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14];
>> H = [0.0400 1.0000 2.2500 9.0000 1.0000 17.6400 9.8596];
for n = 1:7
V(n) = 1/12*pi*(D(n)^2)*H(n);
end
>> V
V =
0.0004 0.2618 1.3254 21.2058 0.2618 81.4640 25.4500
</code></pre>
<p><br />
With MATLAB, you can perform the calculation for each element of a vector with similar syntax as the scalar case,</p>
<pre><code class="language-matlab">>> V = 1/12*pi*(D.^2).*H; % Vectorized Calculation
>> V
V =
0.0004 0.2618 1.3254 21.2058 0.2618 81.4640 25.4500
</code></pre>
<p><br /></p>
<blockquote>
<b>NOTE</b><br /><br />
Placing a period (<code>.</code>) before the operators <code>*</code>, <code>/</code>, and <code>^</code>, transforms them into array operators.
</blockquote>
<p><br /></p>
<h3 id="logical-array-operations">Logical array operations</h3>
<p>MATLAB comparison operators also accept vector inputs and return vector outputs. For example, suppose while collecting data from 10,000 cones, you record several negative values for the diameter. You can determine which values in a vector are valid with the <code>>=</code> operator,</p>
<pre><code class="language-matlab">>> D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14];
>> D >= 0
ans =
0 1 1 1 0 1 1
>> class(ans)
ans =
logical
</code></pre>
<p><br />
You can directly exploit the logical indexing power of MATLAB to select the valid cone volumes, <code>Vgood</code>, for which the corresponding elements of D are nonnegative,</p>
<pre><code class="language-matlab">>> Vgood = V(D >= 0) % removing all data corresponding to negative diameters
Vgood =
0.2618 1.3254 21.2058 81.4640 25.4500
</code></pre>
<p><br />
MATLAB allows you to perform a logical AND or OR on the elements of an entire vector with the functions all and any, respectively. You can throw a warning if all values of <code>D</code> are below zero,</p>
<pre><code class="language-matlab">if all(D < 0) % gives no warning because not all values are negative
warning('All values of diameter are negative.')
end
</code></pre>
<p><br />
or,</p>
<pre><code class="language-matlab">>> if (D < 0)
warning('Some values of diameter are negative.')
end
Warning: Some values of diameter are negative.
</code></pre>
<p><br />
MATLAB can also compare two vectors of the same size, allowing you to impose further restrictions. This code finds all the values where <code>V</code> is nonnegative and <code>D</code> is greater than <code>H</code>,</p>
<pre><code class="language-matlab">>> D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14];
>> H = [0.0400 1.0000 2.2500 1.5000 1.0000 0.6400 9.8596];
>> V((V >= 0) & (D > H))
ans =
21.2058 81.4640
>> V
V =
0.0004 0.2618 1.3254 21.2058 0.2618 81.4640 25.4500
>> (V >= 0) & (D > H)
ans =
0 0 0 1 0 1 0
</code></pre>
<p><br />
The resulting vector is the same size as the inputs. To aid comparison, MATLAB contains special values to denote <strong>overflow</strong>, <strong>underflow</strong>, and <strong>undefined operators</strong>, such as <strong>inf</strong> and <strong>nan</strong>. Logical operators <a href="https://www.mathworks.com/help/matlab/ref/isinf.html" target="_blank">isinf</a> and <a href="https://www.mathworks.com/help/matlab/ref/isnan.html" target="_blank">isnan</a> exist to help perform logical tests for these special values. For example, it is often useful to exclude <code>NaN</code> values from computations,</p>
<pre><code class="language-matlab">>> x = [2 -1 0 3 NaN 2 NaN 11 4 Inf];
>> xvalid = x(~isnan(x))
xvalid =
2 -1 0 3 2 11 4 Inf
</code></pre>
<p><br /></p>
<blockquote>
<b>NOTE</b><br /><br />
Note that <code>Inf == Inf</code> returns <code>true</code>; however, <code>NaN == NaN</code> always returns <code>false</code> in MATLAB.
</blockquote>
<p><br /></p>
<h3 id="matrix-operations">Matrix Operations</h3>
<p>Matrix operations act according to the rules of linear algebra. These operations are most useful in vectorization if you are working with multidimensional data. Suppose you want to evaluate a function, $F$, of two variables, $x$ and $y$,</p>
<script type="math/tex; mode=display">F(x,y) = x*\exp(-x2 - y2) ~.</script>
<p>To evaluate this function at every combination of points in the $x$ and $y$, you need to define a grid of values,</p>
<pre><code class="language-matlab">>> x = -2:0.2:2;
>> y = -1.5:0.2:1.5;
>> [X,Y] = meshgrid(x,y);
>> F = X.*exp(-X.^2-Y.^2);
</code></pre>
<p><br />
Without <code>meshgrid()</code>, you might need to write two for loops to iterate through vector combinations. The function <code>ndgrid()</code> also creates number grids from vectors, but unlike <code>meshgrid()</code>, it can construct grids beyond three dimensions. <code>meshgrid()</code> can only construct 2-D and 3-D grids.</p>
<p>The following table contains a list of MATLAB functions that are commonly used in vectorized codes,</p>
<table class="center">
<caption class="title" style="padding-bottom:10px;text-align:center;">
Table of MATLAB's most-widely used vectorization functions.
</caption>
<thead>
<tr>
<th><font size="4rm" color="red">Function</font></th>
<th><font size="4rm" color="red">Description</font></th>
</tr>
</thead>
<tbody>
<tr><td><code>all</code></td><td>Determine if all array elements are nonzero or true</td></tr>
<tr><td><code>any</code></td><td>Determine if any array elements are nonzero</td></tr>
<tr><td><code>cumsum</code></td><td>Cumulative sum</td></tr>
<tr><td><code>diff</code></td><td>Differences and Approximate Derivatives</td></tr>
<tr><td><code>find</code></td><td>Find indices and values of nonzero elements</td></tr>
<tr><td><code>ind2sub</code></td><td>Subscripts from linear index</td></tr>
<tr><td><code>ipermute</code></td><td>Inverse permute dimensions of N-D array</td></tr>
<tr><td><code>logical</code></td><td>Convert numeric values to logicals</td></tr>
<tr><td><code>meshgrid</code></td><td>Rectangular grid in 2-D and 3-D space</td></tr>
<tr><td><code>ndgrid</code></td><td>Rectangular grid in N-D space</td></tr>
<tr><td><code>permute</code></td><td>Rearrange dimensions of N-D array</td></tr>
<tr><td><code>prod</code></td><td>Product of array elements</td></tr>
<tr><td><code>repmat</code></td><td>Repeat copies of array</td></tr>
<tr><td><code>reshape</code></td><td>Reshape array</td></tr>
<tr><td><code>shiftdim</code></td><td>Shift dimensions</td></tr>
<tr><td><code>sort</code></td><td>Sort array elements</td></tr>
<tr><td><code>squeeze</code></td><td>Remove singleton dimensions</td></tr>
<tr><td><code>sub2ind</code></td><td>Convert subscripts to linear indices</td></tr>
<tr><td><code>sum</code></td><td>Sum of array elements</td></tr>
</tbody>
</table>
<p><br /></p>
<h3 id="why-is-vectorized-code-faster-than-for-loops">Why is vectorized code faster than for-loops?</h3>
<p>The reason for the speedup in vectorized has to sought in the way the memory of computer is built. The figure below represents a schematic diagram of the Central Processing Unit (CPU) of every modern computer in relationship with computer memory.</p>
<figure>
<img src="http:/ICP2017F/lecture/10/cpu-memory.jpg" width="900" />
<figcaption style="text-align:center">
The hierarchy of memory in most modern computers and its relationship with the CPU.
</figcaption>
</figure>
<p>At the highest level of memory hierarchy, closest to the CPU, we have the CPU register. A processor register is a quickly accessible location available to a computer’s CPU. Registers usually consist of a small amount of fast storage and may be read-only or write-only. The CPU has super fast access to data stored in register. But the problem is that this memory is very small, typically on the orders of bits of information.</p>
<p>At the second level of the hierarchy of memory, we have the CPU cache, typically comprised of three different levels L1, L2, L3, which rank from fastest to slowest respectively, in terms of CPU access. However, the faster the cache memory, the smaller it is. Thereofore, L1 is the fastest of the three, but also the smallest of the three levels.</p>
<p>CPU Caching was invented to solve a significant problem. In the early decades of computing, main memory was extremely slow and incredibly expensive — but CPUs weren’t particularly fast, either. Starting in the 1980s, the gap began to widen quickly. Microprocessor clock speeds took off, but memory access times improved far less dramatically. As this gap grew, it became increasingly clear that a new type of fast memory was needed to bridge the gap. See the figure below.</p>
<figure>
<img src="http:/ICP2017F/lecture/10/CPU-DRAM.png" width="900" />
<figcaption style="text-align:center">
The growing gap between the speed of DRAM memories and CPUs in time.
</figcaption>
</figure>
<p>After CPU cache, there the Random Access Memory (RAM) which you hear the most about, when you go to buy a new computer. Typical computers contain 4-32 Gb of RAM. When you open MATLAB and create some variables, all of your data is stored on this memory. However, this memory is the slowest of all in terms of access to CPU.</p>
<p>When you use for-loops in MATLAB to perform some specific calculations on a vector, you are asking MATLAB to go to this memory at each loop iteration to fetch an element of the loop, bring it to the CPU, perform the set of operations requested, and send it back to memory. However, the CPU is much more capable than doing a single calculation at a time. Therefore, if you could somehow tell MATLAB to fetch a bulk of elements from your vector and bring them to CPU to perform the requested operations, your code would become much faster. The way to tell MATLAB to do so, is called <strong>vectorization</strong>. By vectorizing your code, you tell MATLAB to bring as much information as possible to the highest memory level close to CPU, in order to perform the operations on all of them simultaneously and return the result for all of them back to the memory all together. This results in much faster code, since nowadays, as the figure above shows, the bottleneck in code performance is not the CPU speed, but the memory access.</p>
<h2 id="measuring-the-performance-of-your-matlab-functions-and-scripts">Measuring the performance of your MATLAB functions and scripts</h2>
<p>MATLAB has several built-in methods of timing how long it takes to run a MATLAB function or script. The <code>timeit()</code> function as well as <code>tic</code> and <code>toc</code>, are in particular very useful. Use the <code>timeit()</code> function for a rigorous measurement of your function’s execution time. Use <code>tic</code> and <code>toc</code> to estimate time for smaller portions of code that are not complete functions.</p>
<p>For additional details about the performance of your code, such as function call information and execution time of individual lines of code, MATLAB has more sophisticated tools such as <em>MATLAB® Profiler</em>.</p>
<h3 id="timing-matlab-functions">Timing MATLAB functions</h3>
<p>To measure the time required to run a function, whether built-in or your own, you can use the <code>timeit()</code> function. The <code>timeit()</code> function calls the user-specified function multiple times, and returns the median of the time measurements. This function takes <strong>a handle to the function whose performance is to be measured</strong> and returns the typical execution time, in seconds.</p>
<p>For example, suppose that you want to measure the performance of MATLAB’s built-in function, <code>isprime()</code> for a given input value to this function. You can compute the time to execute the function using <code>timeit()</code> like the following,</p>
<pre><code class="language-matlab">>> timeit( @()isprime(10^14) ) % pass the function as a handle to timeit()
ans =
0.0787
</code></pre>
<p><br />
Note that, this function <code>isprime()</code> will have different performance given different input numbers,</p>
<pre><code class="language-matlab">>> timeit( @()isprime(10^4) ) % pass the function as a handle to timeit()
ans =
2.0402e-05
</code></pre>
<p><br /></p>
<h3 id="time-portions-of-code">Time Portions of Code</h3>
<p>To estimate how long a portion of your program takes to run or to compare the speed of different implementations of portions of your program, you can use MATLAB stopwatch timer functions: <code>tic</code> and <code>toc</code>. Invoking <code>tic</code> starts the timer, and the next <code>toc</code> reads the elapsed time.</p>
<pre><code class="language-matlab">tic
% The program section to time.
toc
</code></pre>
<p><br />
Sometimes programs run too fast for <code>tic</code> and <code>toc</code> to provide useful data. If your code is faster than <strong>1/10 second</strong>, consider timing it while running in a loop, and then average the result to find the time for a single run of the loop.</p>
<h4 id="the-cputime-function-vs-tictoc-and-timeit">The <code>cputime()</code> function vs. <code>tic/toc</code> and <code>timeit()</code></h4>
<p>There is another MATLAB function that can do timing of your scripts or your functions: The <code>cputime()</code> function measures the total CPU time and <strong>sums across all threads (cores) in the CPU</strong>. This measurement is different from the <strong>wall-clock time</strong> that <code>timeit()</code> or <code>tic/toc</code> return, and could be misleading. For example, the CPU time for the pause function is typically small, but the wall-clock time accounts for the actual time that MATLAB execution is paused. Therefore, the wall-clock time might be longer.</p>
<p>If your function uses four processing cores equally, the CPU time could be approximately four times higher than the wall-clock time.</p>
<p>Frequently, your best choice to measure the performance of your code is <code>timeit()</code> or <code>tic</code> and <code>toc</code>. These functions return wall-clock time. Note that, unlike <code>tic</code> and <code>toc</code>, the <code>timeit()</code> function calls your code multiple times, and, therefore, considers the cost of first-time calls to your functions, which are typically more time-consuming than subsequent calls.</p>
<h3 id="some-tips-for-measuring-performance">Some tips for Measuring Performance</h3>
<ul>
<li>Always time a <strong>significant enough</strong> portion of code. Normally, the code that you are timing should <strong>take more than 1/10 second to run</strong>, otherwise the timing may not be very accurate.<br />
<br /></li>
<li>Put the code you are trying to time into a function instead of timing it at the command line or inside a script.<br />
<br /></li>
<li>Unless you are trying to measure <strong>first-time cost of running your code</strong>, run your code multiple times. Use the <code>timeit()</code> function for multiple calls timing of your function.<br />
<br /></li>
<li>Avoid <code>clear all</code> when measuring performance of your MATLAB scripts. This will add additional time to wipe MATLAB workspace from all current existing variable definitions, and therefore contaminate the timing measurements of the actual code in your MATLAB scripts.<br />
<br /></li>
<li>When performing timing measurements, assign your output to a variable instead of letting it default to <code>ans()</code>.</li>
</ul>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/lecture/10-matlab-loops-vectorization">Lecture 10: MATLAB - loops and vectorization</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on October 27, 2017.</p><![CDATA[Announcement 3: Midterm Exam Date and Schedule]]>http:/ICP2017F/announcement/3-midterm-exam-schedule2017-10-25T00:00:00-05:002017-10-25T00:00:00-05:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>The goal of this survey is to find out the most popular vote in class for the midterm exam and its date.</p>
<div align="center">
<script>
(function(t,e,s,n){var o,a,c;t.SMCX=t.SMCX||[],e.getElementById(n)||(o=e.getElementsByTagName(s),a=o[o.length-1],c=e.createElement(s),c.type="text/javascript",c.async=!0,c.id=n,c.src=["https:"===location.protocol?"https://":"http://","widget.surveymonkey.com/collect/website/js/tRaiETqnLgj758hTBazgd_2BAklP6IRJLSSnZF_2FQhOsoqlzlxX39RgVUO8eiKa9A61.js"].join(""),a.parentNode.insertBefore(c,a))})(window,document,"script","smcx-sdk");
</script>
</div>
<p><br /></p>
<h2 id="survey-results">Survey results</h2>
<p>A slight majority (52.87%) of the class voted for cancelling the midterm exam and redistributing its grade to homework, quiz, and the final semester project.</p>
<figure>
<img src="http:/ICP2017F/announcement/3/results.png" width="700" />
</figure>
<figure>
<img src="http:/ICP2017F/announcement/3/numbers.png" width="700" />
</figure>
<p><br /></p>
<p><a href="http:/ICP2017F/announcement/3-midterm-exam-schedule">Announcement 3: Midterm Exam Date and Schedule</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on October 25, 2017.</p><![CDATA[Quiz 3: Solutions - MATLAB branching, functions]]>http:/ICP2017F/quiz/3-solutions-matlab-branching-functions2017-10-23T00:00:00-05:002017-10-23T00:00:00-05:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This is the solution to <a href="3-problems-matlab-branching-functions.html" target="_blank">Quiz 3: Problems - MATLAB branching, functions</a>.</p>
<p>The following figure illustrates the grade distribution for this quiz.</p>
<figure>
<img src="http:/ICP2017F/quiz/gradeDist/gradeHistQuiz3.png" width="700" />
<figcaption style="text-align:center">
Maximum possible points is 1.
</figcaption>
</figure>
<p>This quiz is about branching, if blocks and functions in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> Describe, with an example MATLAB script, the difference between <code>*</code> and <code>.*</code> operators (basically what is the role of <code>.</code> in the later operator? (Hint: describe your answer by multiplying two matrices with each other.)</p>
<p><strong>Answer:</strong></p>
<p>The <code>.*</code> multiplies two arrays A and B element by element and returns the result in C, if <code>C = A .* B</code>. By contrast, the operator <code>*</code> is understood by MATLAB as <a href="https://en.wikipedia.org/wiki/Matrix_multiplication" target="_blank">matrix multiplication (or cross product)</a>. For example,</p>
<pre><code class="language-matlab">>> A = [1 0 3];
>> B = [2 3 7];
>> C = A.*B
C =
2 0 21
</code></pre>
<p><br /><br /></p>
<p><strong>2. </strong> <strong>Vector Dot-Product</strong> Vector dot-product in algebra is defined as the summation of the product of the elements of two vectors of the same size. For example,</p>
<script type="math/tex; mode=display">% <![CDATA[
\begin{align*}
a &= [a_1, a_2, ..., a_n] ~, \\
b &= [b_1, b_2, ..., b_n] ~, \\
a . b &= \sum^n_{i=1} a_i b_i
\end{align*} %]]></script>
<p>where $\sum$ denotes summation notation and $n$ is the number of elements of the vectors. Now, given your current knowledge of mathematical operators in MATLAB, what is the simplest way to get the result of the following dot-product of the two vectors $A$ and $B$,</p>
<script type="math/tex; mode=display">A = [1, 0, 3] \\
B = [2, 3, 7]</script>
<p><strong>Answer:</strong><br />
We discussed in question 1 above, that the operator <code>*</code> in MATLAB performs matrix multiplication. So, all you need to do is to convert the vector <code>B</code> to a column vector using the transpose operator <code>'</code>, in order to get the dot-product result,</p>
<pre><code class="language-matlab">>> A = [1 0 3];
>> B = [2 3 7];
>> C = A * B'
C =
23
</code></pre>
<p><br /><br /></p>
<p><strong>3. </strong> (A) Write a MATLAB function named <code>testString</code> that takes as input, a string and then checks if the input string by the user is the equivalent to <code>'MATLAB</code>’. If it is the correct string, then returns logical value <code>true</code> as the function output, otherwise it returns <code>false</code>. Provide two tests of your function which result in <code>true</code> and <code>false</code> output.</p>
<p><strong>Answer:</strong><br />
Here is an <a href="http:/ICP2017F/quiz/3-solutions/testString.m" target="_blank">implementation</a>.</p>
<pre><code class="language-matlab">>> testString('MATLAB')
ans =
1
>> testString('matlab')
ans =
0
</code></pre>
<p><br />
(B) One can argue that there are two basic ways of comparing two strings in MATLAB. one is using <code>==</code> operator, and the other is with the use of a MATLAB built-in function that we have repeatedly used in our lectures and homework. What is this function, and what is its difference with <code>==</code> operator. If you don’t remember this function’s name, then at least you should be able to explain the major flaw with string comparison using <code>==</code>. Explain it with an example MATLAB script.</p>
<p><strong>Answer:</strong><br />
The MATLAB built-in function for string comparison is <code>strcmp()</code>. This is the correct way of string comparison. The logical <code>==</code> operator is an elemental function, meaning that it assumes the two string being compared are arrays of characters, and therefore, the output of the comparison is also an array of logical values. For example,</p>
<pre><code class="language-matlab">>> '1' == 'amir'
ans =
0 0 0 0
>> '12' == 'amir'
Error using ==
Matrix dimensions must agree.
>> strcmp('1','amir')
ans =
0
>> strcmp('12','amir')
ans =
0
>> strcmp('amir','amir')
ans =
1
>> 'amir' == 'amir'
ans =
1 1 1 1
</code></pre>
<p><br /><br /></p>
<p><strong>4. </strong> If you recall from the lectures, MATLAB has two operators corresponding to logical operator <strong>OR</strong>: <code>|</code> and <code>||</code>. There are two minor differences between the two if you recall from our discussions in class. One is about code efficiency, and the other relates to whether we are operating on logical <em>vectors</em> or <em>scalars</em>. Describe which operator improves code efficiency and why. For the second difference, you could also provide an example to describe what each operator does.</p>
<p><strong>Answer:</strong><br />
Recall from our discussions in class that <code>||</code> does short-circuiting, meaning that, if the first element is true, the result of the expression involving OR operator will be true regardless of the rest of the logical expression. For example, <code>true OR x</code> will evaluate to <code>true</code> whatever logical value <code>x</code> might have. Therefore, MATLAB has a special operator <code>||</code> for the logical operator OR, that avoids the calculation of the rest of the logical OR expression, if it is not needed, thus, increasing the speed of your code by avoiding unnecessary logical calculations. The second difference is that, the operator <code>||</code> is for scalar operations, for example, the following logical operation will lead to an error,</p>
<pre><code class="language-matlab">>> [true true] || [true false]
Operands to the || and && operators must be convertible to logical scalar values.
</code></pre>
<p><br />
The correct operator for elemental logical OR operation is,</p>
<pre><code class="language-matlab">>> [true true] | [true false]
ans =
1 1
</code></pre>
<p><br /><br /></p>
<p><strong>5. </strong> Recall that in MATLAB <code>true</code> and <code>false</code> are equivalent to <code>0</code> and <code>1</code>,</p>
<pre><code class="language-matlab">>> true == 1
ans =
1
>> false == 0
ans =
1
</code></pre>
<p><br />
Now knowing this, consider the following MATLAB calculation,</p>
<pre><code class="language-matlab">>> a = 1;
>> b = 0;
>> x = a/b>10.0
x =
1
</code></pre>
<p><br />
Note that $1/0$ is mathematically undefined (but MATLAB by convention, assumes that $1/0\equiv\infty$). Suppose MATLAB’s default behavior is not what you would like to get, that is, you don’t want $x=1$ when $b=0$, but instead $x=0$. What would be the simplest change to the logical expression <code>x=a/b>10.0</code> such that the result is $x=0$ whenever $b=0$.</p>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">>> a = 1;
>> b = 0;
>> x = (b~=0) && (a/b>10.0)
x =
0
</code></pre>
<p><br />
This way, the expression <code>(a/b>10.0)</code> will not be evaluated when $b=0$, and <code>(b~=0)</code> will be returned as the value of <code>x</code>.</p>
<p><br /><br /></p>
<p><strong>6. </strong> <strong>Array of Structures vs. Structures of Arrays.</strong> Suppose you would like to store information about students in a class. You create a array of structures like the following,</p>
<pre><code class="language-matlab">>> AOS(1).grade = 20;
>> AOS(1).name = 'foobar1';
>> AOS(1).grade = 20;
>> AOS(1).name = 'foobar2';
>> AOS(1).grade = 30;
>> AOS(1).name = 'foobar1';
>> AOS(1).grade = 90;
>> AOS(1).name = 'foobar2';
>> AOS(1).name = 'foobar1';
>> AOS(1).grade = 90;
>> AOS(2).name = 'foobar2';
>> AOS(2).grade = 100;
>> AOS(3).name = 'foobar3';
>> AOS(3).grade = 85;
>> AOS
AOS =
1x3 struct array with fields:
name
grade
</code></pre>
<p><br />
Alternatively, you could create a structure array for the same data, like the following,</p>
<pre><code class="language-matlab">>> SOA.names = {'foobar1','foobar2','foobar3'};
>> SOA.grades = [90,100,85];
>> SOA
SOA =
names: {'foobar1' 'foobar2' 'foobar3'}
grades: [90 100 85]
</code></pre>
<p><br />
Suppose you have 10000 students in your class. Which one of these representations do you think would be more computationally efficient to represent the student data, in order to calculate the average grade in you class? Why? (the explanation is brief, you don’t need to write a paragraph.)</p>
<p><strong>Answer:</strong><br />
<em>Structure of arrays</em> is much more efficient for storing grade data. As we discussed repeatedly in class, this is due to the fact that data is stored sequentially in computer memory. Therefore, it would be much easier for the computer to fetch data from memory when all grade data is stored in an array sequentially in memory, than when each grade is separated from the next student’s grade by their names, just as in <em>array of structures</em>.</p>
<p><br /><br /></p>
<p><strong>7. </strong> Write a function <code>getRoot()</code> that takes in three coefficients $(a,b,c)$ of a quadratic equation $ax^2+bx+c$ and outputs the roots of this equation as the function output result.</p>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">function [x1,x2] = getRoot(a,b,c)
d = sqrt(b^2 - 4*a*c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end
</code></pre>
<pre><code class="language-matlab">>> [r1,r2] = getRoot(1,1,1)
r1 =
-0.5000 + 0.8660i
r2 =
-0.5000 - 0.8660i
</code></pre>
<p><br /><br /></p>
<p><strong>8. </strong> Write a MATLAB anonymous function that calculates the following integral, for arbitrary input integration limits $[a,b]$ and coefficient $c$,</p>
<script type="math/tex; mode=display">f(a,b,c) = \int^b_a \big( x^2 + cx + 1 \big) \operatorname{d}x</script>
<p>Write your function such that it takes the three variables collectively as a structure.</p>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">f = @(in) (integral(@(x) (x.^2 + in.c*x + 1),in.a,in.b));
</code></pre>
<p><br /><br /></p>
<p><strong>9. </strong> Write a function <code>getFac()</code> that calculates the factorial of an input integer $n$ (no need for robust coding, assume the input variable is indeed a positive integer).</p>
<script type="math/tex; mode=display">n! = n \times (n-1) \times \cdots \times 1 ~.</script>
<p><strong>Answer:</strong></p>
<pre><code class="language-matlab">function result=getFactorial(x)
if (x<=0)
result=1;
else
result=x*getFactorial(x-1);
end
end
</code></pre>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/3-solutions-matlab-branching-functions">Quiz 3: Solutions - MATLAB branching, functions</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on October 23, 2017.</p><![CDATA[Quiz 3: Problems - MATLAB branching, functions]]>http:/ICP2017F/quiz/3-problems-matlab-branching-functions2017-10-23T00:00:00-05:002017-10-23T00:00:00-05:00Amir Shahmoradihttp:/ICP2017Famir@ices.utexas.edu
<p>This quiz is about branching, if blocks and functions in MATLAB.</p>
<p><br /></p>
<hr />
<hr />
<p><br /></p>
<p><strong>1. </strong> Describe, with an example MATLAB script, the difference between <code>*</code> and <code>.*</code> operators (basically what is the role of <code>.</code> in the later operator? (Hint: describe your answer by multiplying two matrices with each other.)</p>
<p><br /><br /></p>
<p><strong>2. </strong> <strong>Vector Dot-Product</strong> Vector dot-product in algebra is defined as the summation of the product of the elements of two vectors of the same size. For example,</p>
<script type="math/tex; mode=display">% <![CDATA[
\begin{align*}
a &= [a_1, a_2, ..., a_n] ~, \\
b &= [b_1, b_2, ..., b_n] ~, \\
a . b &= \sum^n_{i=1} a_i b_i
\end{align*} %]]></script>
<p>where $\sum$ denotes summation notation and $n$ is the number of elements of the vectors. Now, given your current knowledge of mathematical operators in MATLAB, what is the simplest way to get the result of the following dot-product of the two vectors $A$ and $B$,</p>
<script type="math/tex; mode=display">A = [1, 0, 3] \\
B = [2, 3, 7]</script>
<p><br /><br /></p>
<p><strong>3. </strong> (A) Write a MATLAB function named <code>testString</code> that takes as input, a string and then checks if the input string by the user is the equivalent to string <code>'MATLAB'</code>. If it is the correct string, then returns logical value <code>true</code> as the function output, otherwise it returns <code>false</code>. Provide two tests of your function which result in <code>true</code> and <code>false</code> output.<br />
<br />
(B) One can argue that there are two basic ways of comparing two strings in MATLAB. one is using <code>==</code> operator, and the other is with the use of a MATLAB built-in function that we have repeatedly used in our lectures and homework. What is this function, and what is its difference with <code>==</code> operator. If you don’t remember this function’s name, then at least you should be able to explain the major flaw with string comparison using <code>==</code>. Explain it with an example MATLAB script.</p>
<p><br /><br /></p>
<p><strong>4. </strong> If you recall from the lectures, MATLAB has two operators corresponding to logical operator <strong>OR</strong>: <code>|</code> and <code>||</code>. There are two minor differences between the two if you recall from our discussions in class. One is about code efficiency, and the other relates to whether we are operating on logical <em>vectors</em> or <em>scalars</em>. Describe which operator improves code efficiency and why. For the second difference, you could also provide an example to describe what each operator does.</p>
<p><br /><br /></p>
<p><strong>5. </strong> Recall that in MATLAB <code>true</code> and <code>false</code> are equivalent to <code>0</code> and <code>1</code>,</p>
<pre><code class="language-matlab">>> true == 1
ans =
1
>> false == 0
ans =
1
</code></pre>
<p><br />
Now knowing this, consider the following MATLAB calculation,</p>
<pre><code class="language-matlab">>> a = 1;
>> b = 0;
>> x = a/b>10.0
x =
1
</code></pre>
<p><br />
Note that $1/0$ is mathematically undefined (but MATLAB by convention, assumes that $1/0\equiv\infty$). Suppose MATLAB’s default behavior is not what you would like to get, that is, you don’t want $x=1$ when $b=0$, but instead $x=0$. What would be the simplest change to the logical expression <code>x=a/b>10.0</code> such that the result is $x=0$ whenever $b=0$.</p>
<p><br /><br /></p>
<p><strong>6. </strong> <strong>Array of Structures vs. Structures of Arrays.</strong> Suppose you would like to store information about students in a class. You create a array of structures like the following,</p>
<pre><code class="language-matlab">>> AOS(1).grade = 20;
>> AOS(1).name = 'foobar1';
>> AOS(1).grade = 20;
>> AOS(1).name = 'foobar2';
>> AOS(1).grade = 30;
>> AOS(1).name = 'foobar1';
>> AOS(1).grade = 90;
>> AOS(1).name = 'foobar2';
>> AOS(1).name = 'foobar1';
>> AOS(1).grade = 90;
>> AOS(2).name = 'foobar2';
>> AOS(2).grade = 100;
>> AOS(3).name = 'foobar3';
>> AOS(3).grade = 85;
>> AOS
AOS =
1x3 struct array with fields:
name
grade
</code></pre>
<p><br />
Alternatively, you could create a structure array for the same data, like the following,</p>
<pre><code class="language-matlab">>> SOA.names = {'foobar1','foobar2','foobar3'};
>> SOA.grades = [90,100,85];
>> SOA
SOA =
names: {'foobar1' 'foobar2' 'foobar3'}
grades: [90 100 85]
</code></pre>
<p><br />
Suppose you have 10000 students in your class. Which one of these representations do you think would be more computationally efficient to represent the student data, in order to calculate the average grade in you class? Why? (the explanation is brief, you don’t need to write a paragraph.)</p>
<p><br /><br /></p>
<p><strong>7. </strong> Write a function <code>getRoot()</code> that takes in three coefficients $(a,b,c)$ of a quadratic equation $ax^2+bx+c$ and outputs the roots of this equation as the function output result.</p>
<p><br /><br /></p>
<p><strong>8. </strong> Write a MATLAB anonymous function that calculates the following integral, for arbitrary input integration limits $[a,b]$ and coefficient $c$,</p>
<script type="math/tex; mode=display">f(a,b,c) = \int^b_a \big( x^2 + cx + 1 \big) \operatorname{d}x</script>
<p>Write your function such that it takes the three variables collectively as a structure.</p>
<p><br /><br /></p>
<p><strong>9. </strong> Write a function <code>getFac()</code> that calculates the factorial of an input integer $n$ (no need for robust coding, assume the input variable is indeed a positive integer).</p>
<script type="math/tex; mode=display">n! = n \times (n-1) \times \cdots \times 1 ~.</script>
<p><br /><br /></p>
<p><a href="http:/ICP2017F/quiz/3-problems-matlab-branching-functions">Quiz 3: Problems - MATLAB branching, functions</a> was originally published by Amir Shahmoradi at <a href="http:/ICP2017F">COE 301 - Fall 2017 - MWF 9-10 AM - UTC 4.110</a> on October 23, 2017.</p>