MATLAB Logbook
Personal Details
- Name: William Fayers
- Course: MTH1006 - Computer Algebra and Technical Computing
- Academic Year: 2023-2024
- Institution: University of Lincoln, School of Mathematics and Physics
Declaration
I confirm that this logbook is all my own work and that all references and quotations from both primary and secondary sources have been fully identified and properly acknowledged - William Fayers
Week 1 (25/09/2023 - 01/10/2023)
Summary
- Completed on-boarding for MATLAB
Reflection
- Fairly simple at the minute, but it got pretty interesting towards the end of Onramp - I’m looking forward to how I can use MATLAB to further improve my mathematics!
Week 2 (02/10/2023 - 08/10/2023)
Summary
Today, I worked on several MATLAB exercises:
2.1 Calculator:
- I used MATLAB to determine mathematical operations including basic arithmetic, trigonometric functions, logarithms, and complex calculations.
- Additionally, I calculated the area of a circle with a given radius and used the
helpcommand to understand the function ofacos.
2.2 Variables:
- I practiced setting and manipulating various variables in MATLAB. This included performing arithmetic on these variables and updating their values.
- I also learned to use previous commands for convenience through up/down arrow keys.
2.3 Variable Names:
- I explored different potential variable names to determine which ones are valid in MATLAB. This helped me understand naming conventions and restrictions in MATLAB.
2.4 Scripts:
- I created a MATLAB script named
my_script, where I assigned values to variables and computed an equation. - After writing the script, I executed it to determine the value of the equation.
2.5 Vectors and Intrinsic Functions:
- I worked with vectors, learning to create them using the colon operator.
- I also utilized
linspaceto produce vectors and applied different mathematical functions to these vectors.
2.6 Complex Numbers:
- I delved into complex number operations, calculating products, magnitudes, and other properties of complex numbers.
- Using MATLAB functions like
imagandreal, I extracted the imaginary and real parts of specific complex numbers respectively. - I also determined the argument of a complex fraction.
Exercises
2.1 Calculator
Calculator Code Output (MATLAB)
- Use MATLAB to determine:
- (a)
- (b)
- (c)
- (d)
- (e)
- (f)
- (g)
- (h)
- (i)
- The radius of a circle is 6. Calculate the area of the circle using MATLAB. Hint:
- Look up the command
acosusing the commandhelp, and calculate for . Divide the answer by to write the result as a fraction of .
2.2 Variables
Variables Code Output (MATLAB)
- Set a variable
aequal to7/3,bequal to9/6. Finally, set a variablecequal toa · b. What isc? - Create a variable
myageand store your age in it. Subtract two from the value of the variable, and update the variablemyagewith this new value. Add one to the value of the variable, and update the variable again. Observe the Workspace Window and Command History Window as you do this. - Set a variable
xequal to10. Increase the content of the variable by1. Now multiply the content of the variable by a factor2. What is the value ofx? - Set a variable
requal to6. Set another variable equal to (by referring to the variabler), to calculate the area of a circle. Increase the radius by2and re-calculate the area. Hint: you can use the up/down arrows on the keyboard to re-use a previously typed command. Afterwards, repeat the calculation for a radius of . DoesAneed to be updated?
2.3 Variable names
Variable Names Code Output (MATLAB)
- Test and tell for each of the following names if it is a valid variable name. Hint: see if it appears in your workspace, if you try to assign a value to it.
- (a)
xValid - (b)
x2Valid - (c)
2xInvalid - (d)
xyValid - (e)
x xInvalid - (f)
exc3.1Invalid - (g)
tanValid - (h)
ifInvalid - (i)
endInvalid - (j)
a long variable nameInvalid - (k)
a_long_variable_name2Valid - (l)
x$Invalid - (m)
x%Invalid - (n)
a_Valid - (o)
_aInvalid
- (a)
2.4 Scripts
- (a) Create a script with the name
my_script, by typing in the command line:edit my_scriptNote that MATLAB will automatically add the extension.m, so one does not need to type this.- (b) In the script set
a = 1,b = 2,c = 3,x = 4and then set a variable to . - (c) Execute the script by typing in the name of the script on the command line (without the extension
.m). What is the value of ?
- (b) In the script set
2.5 Vectors and intrinsic functions
- Use the colon,
:, to create a vector of integers starting from11to20. Hint: Use thehelpfunction for:for more information - Use the colon operator to:
- (a) create a vector of integers starting from
100to110with step2 - (b) create a vector starting from
100to110with step0.1
- (a) create a vector of integers starting from
- Use
linspaceto create a vector from11to20with50elements. - Create a vector of
10elements between0and3, set the result in a variablex, and then calculate for all these values at once. - Create a vector
xcontaining the values0.1, 0.2, 0.3, . . . , 1.0and hence find the following functions of the entries:- (a) The hyperbolic sine. Hint: use
lookfor hyperbolic - (b) The natural logarithm.
- (c) The base-10 logarithm.
- (a) The hyperbolic sine. Hint: use
2.6 Complex numbers
Complex Numbers Code Output (MATLAB)
- Calculate:
- (a)
- (b)
- (c)
- (d)
- (e)
- Set
xto the imaginary part oftan(i). What is the value ofx? Hint:imag. - Set
x2to the real part of . What is the value ofx2? Hint:real. - Determine the argument of using MATLAB.
Reflection
- This week was again fairly simple, but got me even more excited on how I can use MATLAB for more complex mathematics. This week also gave me my first challenge, where I thought I backed up my notes and then accidentally deleted them… but my back-ups weren’t working. So, outside of lecture hours I did some self-study to recreate them all (including this logbook).
- I also thought some of the commands were interesting - such as using angle() instead of arg().
- Hopefully I’ll get used to multiplying by explicitly saying * too! It’s pretty tricky to remember, especially with things like being written as
2*pi.
Week 3 (09/10/2023 - 15/10/2023)
Summary
- Plotted sin(x), cos(x), and various quadratic functions, refining with legends and specific styles.
- Worked with vector indexing, extracting and calculating using elements.
- Tackled mathematical series and fractional sums using vector operations.
- Manipulated and merged strings, making specific modifications.
- Evaluated a range of Boolean expressions and made string comparisons.
Exercises
3.1 Plotting
-
Plotting sin(x) and cos(x)
- Create a script that plots the function for using an interval in of .
- On the same figure plot with a dashed, red line.
- The x-axis should be in the range to .
- Include a legend.
- Save the resulting plots as
.pngfiles with the name as the exercise number.
-
Plotting Quadratic Curves
- Plot the four curves for , with (use at least 100 points).
- Hint: get help on the command
hold.
-
Custom Plot of
- Create a plot for in the range -0.5 to 1.5 with the following features:
- The curve should be a black broken line.
- Label the y-axis as ‘This is the y axis’.
- x-values range: -0.5 to 1.5.
- y-values range: 0 to 1.
- Title: ‘Plot of the function . Author: [Your name]’
- Create a plot for in the range -0.5 to 1.5 with the following features:
3.2 Vector indexing – one element
Vector Indexing - One Element Code Output (MATLAB)
- Vector Creation and Indexing
- (a) Create a vector of 5 elements ranging from 2 to 4 (equally spaced), and store in variable
v. - (b) Store the first element in
x. - (c) Store the last element in
y. - (d) Store the third element in
z. - (e) Calculate . Verify your answer by hand.
- (a) Create a vector of 5 elements ranging from 2 to 4 (equally spaced), and store in variable
3.3 Vector operations
Vector Operations Code Output (MATLAB)
-
Mathematical Series
- (a) Calculate
- (b) Calculate
-
Vector-based Sums
- (a) Find the sum:
- (b) Calculate:
-
Vector and Scalar Variables
- (a) Set a scalar variable
maxxto the maximum of the vectorx. - (b) Set a vector variable
cosxto the for all values ofx. - (c) Set a scalar variable
meanxto the average ofx.
- (a) Set a scalar variable
3.4 Strings
- String Manipulations
- (a) Create a string ‘this is a string’ and store in variable
s. - (b) Create a string named
s1with contents ‘this is ‘. - (c) Create a string named
s2with contents ‘a string’. - (d) Combine the two strings in a new variable
stot. - (e) Change the first element of
stotto ‘T’. - (f) Add an exclamation mark to the end of
stot.
- (a) Create a string ‘this is a string’ and store in variable
3.5 Boolean algebra
Boolean Algebra Code Output (MATLAB)
-
Boolean Comparisons
- Determine the following:
- (a)
- (b)
- (c) or
- (d)
- (e)
- (f) not false
- (g) true and (true or false)
- Determine the following:
-
Variable Comparisons
- Set a variable
nequal to . - Set
b1equal to . - Set variable
b2equal to ‘notb1’. What is the content of variableb2?
- Set a variable
-
String Comparisons
- Create a string named
swith contents ‘hi’. - Determine if it is equal to the following using
strcmp:- (a) ‘Hii’
- (b) ‘hi’
- (c) ‘Hi’
- (d) ‘hi ’
- Create a string named
Reflection
- This session was again very simple, although I did notice I needed a few minutes to relearn the commands from the last few weeks - this week I think I’ll do some independent work from a library book to keep me from forgetting everything.
Week 4 (16/10/2023 - 22/10/2023)
Summary
- Today, I worked on three main tasks in MATLAB:
- Output Commands:
- Used
dispcommand to display strings. - Created scripts to output numerical values as strings.
- Used
- Conditional Branching:
- Practiced with
ifstatements to evaluate and display conditions. - Developed a script to compare temperatures between two days.
- Practiced with
- Functions:
- Completed some modules in MATLAB Academy under MATLAB Fundamentals.
- Created and modified a function
area_circleto calculate the area of a circle, and adjusted it to handle different input types and scenarios.
- Output Commands:
Exercises
4.1 Output
- Output the string
This string has been written to the screenusing thedispcommand. - Write a script that sets the variable to and then outputs a string from . Hint: use
num2str. - Write a script that sets a number to the variable and subsequently outputs the text
The temperature is ...where the dots have to be replaced by the actual number contained in . For example, if , the output should beThe temperature is 37.
4.2 Conditional Branching
Conditional Branching Code Output (MATLAB)
-
Write a script that sets to a value. Then use the
ifstatement to test if the number is larger than . If it is larger than zero, then write to the screen thatThis number is larger than zero. Run the script with a positive and with a negative number. -
(a) Write a script that sets the variable
Saturdayto , and the variableSundayto . (b) Add at the end anifstatement that displays the stringSaturday is colderifSaturday < Sunday. (c) Add anotherifstatement, which displays the stringSunday is colder, ifSunday < Saturday. (d) Add anotherifstatement, which displays the stringBoth days have the same temperature, if the two variables are equal. (e) Change the first line of the script so thatSaturdayequals and make sure the script runs as expected. (f) Do the same forSaturdayequal to . -
Create a script named
testnumber.m: (a) At the start of the script, set a variable to . (b) Add anifstatement to test if the imaginary part of is unequal to (this implies it is a complex number). If this is the case, then multiply by its complex conjugate (see help ofconj), take the square root of this and store the result in . Also set a string namedstothis is a complex number. (c) Add anotherifstatement, such that if the number is not complex (imaginary part is ), then just square the number and take the square root of it, and store the result in . In this case, also set the string namedstothis is a real number. (d) How would you test if the number is a integer (whole) number? Implement this as well in the script, including an appropriate string. (e) Test the script by changing the value of in the beginning of the script to (i) a real number and (ii) an integer.
4.3 Functions
Functions Code Output (MATLAB)
-
Go to MATLAB Academy, login using the credentials you created during week , and open the course MATLAB Fundamentals. Complete: (a)
Increasing automation with functions: Creating and Calling Functions (15.1)(b)Increasing automation with functions: Function Files (15.2)(c)Increasing automation with functions: Workspaces (15.3) -
In this exercise a user-defined function will be created: (a) Start by creating a new file, named
area_circle, usingedit area_circlein the command line. (b) Add the following code into this file:function A=area_circle(r) % Calculates the area of a circle given the radius A=pi*r^2; endNotice that is the input argument and is the output argument. (c) Calculate the area of a circle of radius , by calling the function from the command line by typing>> area_circle(4). (d) Call the function for (instead of ). (e) Within the function definition, change the input argument to , and also change the formula to . Test if the function still works by calling it from the command line. (f) Change the output argument toareaand make a similar change in the formula. Test if the function still works by calling it from the command line. (g) Change the comment in the function and observe this comment by typinghelp area_circlein the command line. (h) Now call the function for a vectorradii=[3,4,5]. Does the function work? If not, adjust the function, by replacing^with.^and test it again. (i) Finally, change the function so that a diameter is expected as an input argument. Change the symbol to for this, and adjust the formula accordingly.
Reflection
- Unfortunately I did not get time to do some independent work last week as I planned, and yet again did it display to me how much I should be doing it - it’s so hard to remember everything when you only use it once a week!
Week 5 (23/10/2023 - 29/10/2023)
Summary
- Made an Anki deck for MTH1006
- I developed functions for temperature conversions and plotted exponential curves, incorporating error checks for complex numbers.
- Determined the volume of a cone using its radius and height.
- Calculated various summations, both simple and squared, and expanded to geometric series.
- Crafted functions to evaluate the sum of series, involving squares, cubes, and factorial denominators, and cross-checked manually.
- Implemented a break mechanism in loops to cap the summation based on a set threshold.
- MATLAB Coursework 1 (files)
Exercises
5.1 Functions and scripts
Functions and Scripts Code Output (MATLAB)
-
Celsius to Fahrenheit:
- (a) Write a script that converts a temperature in Celsius to Fahrenheit using the formula:
Subsequently output:
The temperature is ... degrees Celsius, which corresponds to ... degrees Fahrenheit. - (b) Test with: , , .
- (c) Create a function to convert in Celsius to Fahrenheit. Test: and .
- (a) Write a script that converts a temperature in Celsius to Fahrenheit using the formula:
-
Volume of a Cone:
- The volume of a cone is:
Write a function with inputs and , and output the volume. Test for and .
- The volume of a cone is:
-
Plotting Curves:
- (a) Create a function to plot curves of the form:
where with at least 100 points. Inputs: and .
- (b) Create a script to plot curves for:
- (c) Modify function: If or is complex, show error message.
- (d) Test for , , .
- (a) Create a function to plot curves of the form:
5.2 Loops
-
Summations:
- (a) Calculate:
- (b) Calculate:
- (a) Calculate:
-
Find:
-
Calculate:
-
Functions with Sums:
- (a) Function for:
Test for , , .
- (b) Function for:
Test: , , .
- (c) Function for:
Test: and .
- (d) Function for:
Test: , , . Check answers by hand.
- (a) Function for:
-
Loop with Break: Create a script: set and compute:
The sum should not exceed 1,000,000. Break if adding next term exceeds this limit. Test for and .
Reflection
- I did some independent work this week, too, for example learning about sprintf/fprintf which has really helped, as well as integrating the commands into my Anki workflow as flashcards so I don’t forget them.
- A good week for MATLAB!
- I also completed my MATLAB Coursework this week, which was quite fun!
Week 6 (30/10/2023 - 05/11/2023)
Summary
- I delved into complex mathematical calculations using nested loops, focusing on controlling the iteration criteria.
- I experimented with conditional branching by customizing a script. I manipulated case-based responses to different input variables.
- I explored conditional looping, gaining insights into loop termination conditions and avoiding infinite loops. I also applied these concepts to previous exercises for a deeper understanding.
Exercises
6.1 Nested loops
Nested Loops Code Output (MATLAB)
Exercise 1
(a) Calculate for using a nested for loop.
(b) Modify the loop to exclude the terms with .
6.2 Switch Statements
Switch Statements Code Output (MATLAB)
Exercise 1
- Download the script
switch_test.mfrom Blackboard, learning materials.- (a) At the beginning of the script, set a variable called
number_of_countriesto a number, signifying the number of countries in the UK. - (b) Modify the script so that the correct answer is 4 and not 5.
- (c) Add another switch option, if the answer is 5:
'The answer is slightly lower'. - (d) Add another switch option, if the answer is -1 or -2:
'The answer cannot be negative!'. Use the construct with{}. - (e) Test the script for all possible pathways of execution.
- (a) At the beginning of the script, set a variable called
Exercise 2
- Create a script that:
- Sets the variable
nameto a certain value. - By using a
switchstatement, display appropriate messages based on the name.- If it is your own name, display ’Hello, myself’.
- If it is one of your neighbour’s name, display: ’Hello, neighbour!’.
- If it is any other name, display: ’Hello, Stranger’.
- If it is either your surname or your neighbour surname, display: ’Hello, you should have entered your first name’.
- Test it for all five cases
- Sets the variable
Exercise 3
(a) Write a function that tests whether an input argument string is a certain letter. If the input string is anything other than a 'Q', it prints an error message.
(b) Create a function with a switch statement. Test whether the input argument is either 1, 3, or 5, and display the corresponding textual number. If the input is something else, show the message ’Invalid value for the input argument. Test it by calling the function from a script.
6.3 While loop
While Loop Code Output (MATLAB)
Exercise 1
- Given the following loop:
while x < 20 action end- (a) For what value of would the action be skipped entirely? 20
- (b) What would the action have to include to prevent an infinite loop if starts at 5? incrementing x, such that the code would be
x = x + 1after init. xx = 5.
Exercise 2
- Repeat exercise 5.2.1 but now with a
whileloop.
Exercise 3
- Repeat exercise 6.1.1a but now with a nested
whileloop.
Exercise 4
(a) Calculate where is an integer that makes the sum just exceed 100,000. Hint: use a while loop.
(b) Convert the script into a function with input and output arguments.
(c) Modify the function so it returns that doesn’t make the sum exceed a certain number (e.g., 100,000).
Reflection
- The session was okay, again more of the same - the Anki has definitely helped!
Week 8 (13/11/2023 - 19/11/2023)
Summary
7.1 Paths and Programs
- Focused on directory management and function creation in MATLAB.
- Practiced creating and using custom functions and scripts.
- Implemented file path manipulation and command execution.
7.2 Test-riven Development
- Developed functions with specific outputs and tested their accuracy.
- Emphasized on debugging and validating functions using test scripts.
- Explored test-driven development techniques in MATLAB.
Exercises
7.1 Paths and Programs
Paths and Programs Code Output (MATLAB)
Exercise 1
If you do not understand a certain function or command, use the MATLAB help function for more information.
- (a) If the user account that you use to log into the windows computer is User, then go to the folder
C:\Users\User\Documents\MATLAB, by clicking on the current folder, and replacing the text withC:\Users\User\Documents\MATLAB. If you have used a different user name, replace User by your user name. - (b) From within the command window, create a folder called
session7, usingmkdir. - (c) Go to this folder within MATLAB using the command
cd(i.e., typecd session7). - (d) Within this folder, create a function
my_square.mthat squares the input argument number and returns as an output argument this square. - (e) Call the function from the current folder by typing in the name of the function from the command window. Make sure it is working as expected.
- (f) Go to the parent folder, using
cd ... - (g) See if you can run the function from this folder. MATLAB should respond with an error message.
- (h) Go back to the
session7folder, using againcd. - (i) Add the current folder to the path, making use of the functions
addpathandpwd, e.g., useaddpath(pwd). - (j) Go to the parent folder, using the command typed in before.
- (k) See if you can run the function
my_squarefrom this parent folder (if not, something went wrong; try to fix it).
Exercise 2
- (a) If you haven’t done so already, create a folder
session7. Then go to this folder. - (b) From here, create the folders
functionsandscripts. Add the two folders to the path. - (c) In the folder
functions, create a function that calculateslog3(x), i.e., the logarithm with base 3, and returns the result. Call the functionlog3. - (d) In the
scriptsfolder, create a script that first sets a number to a certain value. Then test if the number is larger than zero. If so, calculatelog10(x),log3(x), andlog2(x)of the number, otherwise show an error message. Name the scriptcalc_logs. For thelog3(x)calculation, use your previously created function. - (e) From the folder
session7call the scriptcalc_logs.
Exercise 3
- (a) Create a function
readradiusthat asks the user for a radius. The function should return this radius. - (b) Create a function
calcarea, that has a radius as input argument and returns the area as output argument (see one of the previous exercises). - (c) Create a function
printarea, that has a radius and area as input and usesdispto display “The area of a circle of radius … equals …“. - (d) Finally, create a script that first calls
readradius, thencalcareaand finallyprintarea, while passing appropriate parameters for all these functions.
7.2 Test-Driven Development
Test-Driven Development Code Output (MATLAB)
Exercise 1
Write a function my_nexthour that receives one integer argument, which is an hour of the day, and returns the next hour. This assumes a 12-hour clock, so for example the next hour after 12 would be 1. Here are two examples of calling this function:
>> my_nexthour(3)
ans = 4
>> my_nexthour(12)
ans = 1Test your function for both these values.
Exercise 2
Download the files test_nexthour.m and nexthour.m from Blackboard and place them in a convenient folder (which is not necessarily the Downloads folder).
- (a) The first
asserttest in the script filetest_nexthour.mhas an appropriate error message. Modify the two other tests, so that they also have an appropriate error message. - (b) Add appropriate pass messages after each
assert. - (c) Modify the function
nexthour, by editing the filenexthour.mand fixing the bugs in this file. The behaviour of the functionnexthourshould be the same as the previous exercise. - (d) Add an extra line in the test script, that tests if
nexthour(4)equals 5. - (e) Add an extra line in the test script, that tests if
nexthour(12)is smaller than 13. - (f) Now run the script
test_nexthour, and make sure allasserttests pass.
Exercise 3
- (a) Write a function that, given a scalar
x, returnsx^2 + 2x + 3. Test it withx = 0andx = 1, and check your result by hand. - (b) Create a script with name
test_my_polynomialthat tests the functionmy_polynomial. Test that if this function is given the argument 0, it returns 3, and for the argument 1, it returns 6. The tests should useassertas in the previous exercise onnexthour. - (c) Write a function that, given a vector
x, returnsx^2 + 2x + 3, element-wise. Test it with the vector[1, 2, 3]and check your result by hand. - (d) How would you test this function with vector input in the script
test_my_polynomial?
Reflection
- Basically just navigating Linux and then error-handling. Overall not that exciting stuff, but definitely useful - the “assert” command is also quite interesting.
- Not too many problems, but any problems I did have I could figure out after a short while - mostly syntax.
Week 9 (20/11/2023 - 26/11/2023)
Summary
8.1 File I/O
- Focused on file input/output operations in MATLAB.
- Learned to read from and write to files, and practiced data manipulation from file data.
- Developed skills in plotting data from files and reversing data sequences in files.
8.2 Scope
- Explored the scope of variables in MATLAB, particularly in the context of user-defined functions and command prompt interactions.
- Investigated how local variables behave differently in scripts and functions.
8.3 Debugging
- Practiced debugging techniques in MATLAB.
- Worked with breakpoints, conditional breakpoints, and monitored variable changes during script execution.
Exercises
8.1 File I/O
Exercise 1
- (a) Create the folder
session8, and make this the current MATLAB work directory (you could usecd). - (b) Download both the files
time.txtandtemp.txt(they are in the aforementioned .zip file) and put them in this folder. - (c) Create a script, where you load each file in a variable, using
load(twice). Finally, plot the time of the day in hours vs the temperature of a human in degrees Celsius.
Exercise 2
- (a) Download the file
sample.txtfrom Blackboard (this is in the aforementioned .zip file) and put it in your current MATLAB work directory. - (b) Create a script named
reverse_script.mthat does the following:- (i) Set a string that signifies an input filename in the variable
inputfilename. - (ii) Set a string that signifies an output filename in the variable
outputfilename. - (iii) Reads the data in the input file into a vector (make use of the
loadcommand and the variableinputfilename). - (iv) Reverse the order of the vector (i.e., [1,4,6] should become [6,4,1]), using the
(end:-1:1)indexing method on your vector variable. - (v) Writes the vector to the output file in plain text. You can use the
savecommand for writing the output file with nameoutputfilename. A plain text file in MATLAB is known as ASCII encoding, and can be selected using the option-asciiwithsave, see help.
- (i) Set a string that signifies an input filename in the variable
- (c) Run your script with the input file
sample.txtand output filereversed.txt. Check the contents of the output file by opening it in Microsoft Word or by usingtype reversed.txtin MATLAB. - (d) Run it with input file
reversed.txtand now output filedouble_reversed.txt. Check that the original file is restored, by opening bothsample.txtanddouble_reversed.txt. - (e) Create a function named
reverse_function.mthat has two input arguments:inputfilenameandoutputfilenameand has no output arguments. The function should do the same as thereverse_script.m(except now the lines with the string variables that appeared in your script are now input parameters for the function). Also test this function by calling it from the MATLAB command line, i.e.,reverse_function('sample.txt', 'sample_reversed.txt')and check if the output file contains the expected data.
Exercise 3
- (a) Download the script
fileex.mfrom Blackboard (this is in the aforementioned .zip file). Open a file with namesubjexp.txtby typingedit subjexp.txtat the MATLAB prompt. - (b) Modify the script
fileex.msuch that it displays the sum of the numbers from the file.
Exercise 4
- (a) Write a script that will read from a file x and y data points in the following format:
The format of every line in the file is the letter ‘x’, a space, the x value, space the letter ‘y’, space, and the y value. First, create the data file with 10 lines in this format. Do this by using the editor, then save the file asx 0 y 1 x 1.3 y 2.2xypts.dat. The script will attempt to open the data file and error-check to make sure it was opened. If so, it uses a for loop (since the file contains exactly 10 points) andfgetlto read each line as a string. In the loop, it creates x and y vectors for the data points. After the loop, it plots these points and attempts to close the file. The script should print whether or not the file was closed successfully.
Exercise 5
- (a) Modify the script from the previous problem. Assume that the data file is in exactly the same format, but do not assume that the number of lines in the data file is known a priori. Hence, instead of using a for loop, loop until the end of the file is reached using a while loop. The number of points in the file should be mentioned in the plot title.
8.2 Scope
Exercise 1
- (a) If one sets a local variable within a user-defined function to a value. Can one change this value from the command prompt? No, MATLAB uses function scoping.
- (b) If one sets a local variable within the command prompt, can one change this value from within a user-defined function? No, but it could be set as a global variable - although discouraged.
8.3 Debugging
Exercise 1
- (a) Create a new script with the following piece of code.
It adds the numbers 1 till 5 together.
S=0; x=0; while x<5 x=x+1 S=S+x end - (b) Place a breakpoint at line 6, by clicking on the 6 in the editor. A red indicator will appear. Run the code, and when paused press Continue or enter
dbcontthree times. What are the values of S and x now? Is this what you expect? The code runs as expected, with values at each breakpoint consistent with the logic of the loop. - (c) Now place a conditional breakpoint at line 6, by clicking on the 6 in the editor → right-mouse click → and enter the text
x==3. Then run the program. What is S when the program breaks? Is this what you expected? How many times do you have to press Continue or enterdbcontto end the program? The breakpoints only begin when x is equal to 3 onwards, from which the values are still consistent with the logic of the loop.
Reflection
- Feels like we’re reaching the end of the MATLAB work, and I feel fairly confident using it to help me solve maths problems! I’ve been doing some Project Euler work, too, and it’s been interesting using Python and then using MATLAB to do the same problem.
Week 10 (27/11/2023 - 03/12/2023)
Summary
9.1 Integer and Floating Point Classes
- Explore the range of values for integer and floating-point classes in MATLAB.
- Determine suitable data types for specific applications.
9.2 Matrices for Handling Multiple Numbers
- Learn to manipulate and visualise data stored in matrices.
- Analyse demographic data and temperature records using MATLAB.
Exercises
9.1 Integer and Floating Point Classes
Integer and Floating Point Classes Code Output (MATLAB)
Exercise 1
- (a) Determine the range of values for int8 by generating a positive and negative overflow. Verify results with
intmaxandintmin. - (b) Do the same for uint8.
- (c) Repeat the process for int16.
- (d) Similarly, for uint16.
- Question: Which type would be suitable and most economical for storing the age of a human?
uint8would probably be most economical, as whilstint8would currently work (as the oldest age recorded is around122, which under under the max127), it’d futureproof if the max was instead255and the positive integers would be useful, compared to the negative.
Exercise 2
- Store a number with a decimal place in a double variable, then convert it to int32 and inspect the new variable’s content and size with
whos.
Exercise 3
- Calculate the following using MATLAB and comment on the analytical expectations and any differences:
- (a)
- (b) They both only approach zero, even though they should equal zero.
Exercise 4
- (a) Determine the sum of for to using a for loop and an accumulator
S. 1.1111 - (b) Modify the script to find from what value of
nthe accumulator does not change anymore. Use an extra variableS_prev. n=17 - (c) Change
Sto type single and observe the result. n=9
9.2 Matrices for Handling Multiple Numbers
Matrices for Handling Multiple Numbers Code Output (MATLAB)
Exercise 1
- (a) Create the folder
session9and set it as the current MATLAB work directory. - (b) Download and store the file
yearmalefemale.txtin this folder. - (c) Create a script to:
- Load the data into a matrix.
- Extract the first column into
year, the second intomale, and the third intofemale. - Plot the number of males and females versus the number of years.
- Add appropriate labels and legends.
- (d) Analyse the biggest difference between the male and female graphs. More females than males above the age of ~70 years old.
Exercise 2
- (a) Create the file
averhighs.txtin MATLAB with specified temperature data. - (b) Write a script to read these data and plot the temperatures for three locations in one graph.
- (c) Create a function to convert Fahrenheit to Celsius.
- (d) Plot the converted temperatures with appropriate labels and legend.
Reflection
- It’s interesting applying more and more of my MATLAB knowledge into the problems as they get more difficult, it’s quite fun! I initially struggled to make my script for Exercise 9.2.2 code efficient, but it was a fun problem to solve.
References
- Enter your references here…