This is the solution to Homework 3: Problems - structures, branching and functions in MATLAB.
The following figure illustrates the grade distribution for this homework.
♣ Due Date: Monday Oct 30, 2017 9:00 AM. 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 *.m
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).
1. The bell-shaped Gaussian probability density function,
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$.
Verify your answer by getting the same result from Wolfram Alpha mathematical search engine, also by using MATLAB’s builtin function normpdf($x$,$\mu$,$\sigma$).
Answer:
An example implementation can be found here.
2. 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}$.
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):
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$). (Hint: Note that for this problem you will need to use MATLAB’s builtin function log()
, and the predefined variable pi
.)
Answer:
An example implementation can be found here.
3. Converting polar and Cartesian vector representations using functions and structures. 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,
The relationships between the Cartesian $(x,y)$ and polar $(r,\phi)$ coordinates are given by the following equations,
Write a MATLAB function getPolar(inputCartesianStruct)
that takes a structure inputCartesianStruct
as input, that has two components x
and y
. Then on output, it returns another structure that has to components r
and phi
. Write another function getCart(inputPolarStruct)
that does the inverse of getPolar(inputCartesianStruct)
. Make sure that both functions are robust to wrong input structures by checking whether the input structures have the required fields: x
and y
, or r
and phi
. You can do so by using MATLAB’s builtin function isfield()
.
Answer:
Here is an example implementation of getPolar.m and getCart.m.
4. Calculating the size of a directory The MATLAB function dir
returns the contents of a specified directory. It returns the result in the form of an structure array with four fields, for example,
>> 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'
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.
Answer:
Here is an example implementation of getBytes.m.
5. 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:
with the following sequence equation,
Write a MATLAB function named fib
that takes in an input argument which should be integer number n
, 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,
>> 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
>>
Hint:
- First write a function
getFib(n_int)
that finds the requested Fibonacci number for you, given a strictly non-negative integer input (for example, name itn_int
).
- Then put this function inside another MATLAB function
fib()
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 functioninput()
. Read the input value as astring
using this MATLAB function. Then check if the user’s input string is equivalent to ‘stop’ or not. If it is ‘stop’, then the program must return, otherwise, usestr2double()
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 functionisreal()
. If the value is real, then check if it is a non-negative real number. Also check if it is an integer by comparing the value with its rounded value using MATLAB’s functionround()
. 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 functiongetFib(n_int)
), and then call this functionfib
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 functionfib
again to ask the user for another input.
Answer:
Here is an example implementation of fib.m.
6. 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,
Write a function getTriangleArea(vertices)
that returns the area of a triangle whose vertices are specified by the argument vertices, which is a nested list of the vertex coordinates.
Answer:
Here is an example implementation of getTriangleArea.m.
7. Write a logical (boolean) function named isPrime(n)
that takes in an integer number n
, and finds whether it is a Prime number or not. Example output is the following,
isPrime(23)
True
isPrime(12)
False
Note that you do not need and don’t have to use a for-loop
for this problem (we have not yet discussed loops in our class!). All of it can be done using recursive function concept. You can verify the accuracy of your MATLAB script via by checking its output against MATLAB’s builtin function isprime()
.
Answer:
Here is an example implementation of isPrime.m.
8. Function generators. Write a nested function that evaluates a polynomial of the form $y = ax^2+bx+c$. The host function genFunc()
should be able to take varying number of arguments using varargin
with maximum of 3 arguments (a,b,c
) to initialize the coefficients of the polynomial. If there is only one argument, then b
and c
must be set to zero. If there are two input arguments, then c
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.
On output, the host function should create and return a function handle for the nested function evalFunc()
. 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 function generator, 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 genFunc(1,2,0)
and save the output function handle in a variable, say h1
. Call genFunc(1,2)
and save the output function handle in a variable, say h2
. Then these two function handles, should give the same result, given the same input x
values.
Answer:
Here is an example implementation of genFunc.m.