Worksheet 1
MATLAB Onramp
Complete the MATLAB online course MATLAB Onramp
Workspace Setup
Ensure your MATLAB path is set to
<INSTALLDIR>/i2sc_worksheets/Worksheet1
where <INSTALLDIR> is the directory where you extracted the course content (see the Getting Started page)
1. Basic Arithmetic
Operators needed: =, +, −, /, *, ==, ˆ
Commands needed: sqrt, rem, help
Tasks
Complete the following tasks in the supplied file problem_1.m
- store the value 6 in a variable
x - add two to
x, store the results in the variabley - multiply
yby 2 and subtract half ofxto it, store the results inz - use the
==operator to checkzis equal to 13 - learn how to use the
sqrtcommand: typehelp sqrtinto the command window - store the value 16 in the variable
t. - evaluate the remainder of
tdivided by 3 using the rem command (usehelp) - use the
sqrtcommand to calculate the square root oftand store it inx(note, this will overwrite the previous value of x) - calculate the square of
xusing theˆoperator, store the results int2 - use the
==operator to checkt2is equal tot - set
t=10and repeat steps 8-10.
Spoiler alert - in step 11 you will encounter the unintuitive result that
t2does not equalt. This implies \(\sqrt{10}^2 \ne 10\), which is of course wrong. If you entert2-tin the command line you will note the difference between them is extremely small. This error is due to the limitations of how computers complete arithmetic, and can be replicated in other programming languages such as pythonfrom math import sqrt sqrt(10)**2-10Therefore when checking the equality of floating point numbers (e.g. not integers) it is important to instead check they are within a certain tolerance. In MATLAB a robust method is to use the function
epsto estimate the tolerance. e.g.t = 10; t2 = sqrt(t)^2; abs(t-t2) <= eps(max(abs(t),abs(t2)))Which returns true.
But how does this work? There are an infinite number of numbers, but computers store these numbers with a finite number of bytes. To do this the number line is discretised into a finite set of numbers (see Floating-point arithmetic). If a requested number does not fit on this discretised number line (such as for \(\sqrt{10}\)) the closest floating point number is selected. This rounding error is then propagated in the square operation, leading to a number slightly different from 10.
The function call
eps(10)finds the difference between 10 and the next floating point number on the discretised number line. Hence,abs(t-t2) <= eps(max(abs(t),abs(t2)))ensures the two results are close on the discretised number line.Numbers are not spread evenly on the discretised number line, compare the outputs of
eps(1),eps(10)andeps(10e6)
2. One Dimensional Arrays
Operators needed: =, ==, >, .*,( ), ∼=, −
Commands needed: sum, find, help, doc
Tasks
Complete the following tasks in the supplied file problem_2.m
- create a small 1D array (e.g. a vector), named
A, containing the numbers 0, 2, 5, 8, 9 - replace the fourth value of
Awith the number 1 subtract 1 to each element of
A, and store the result inXMATLAB is case sensitive;
Aandaare different variables- add all the values of
Ausing thesumcommand, and store ins - multiply each element of
Aby itself (i.e. element-wise multiplication), store inB - take the transpose of
A, store inAt - use the find command to find the index of element of
Aequal to 5, store the result inid5. Ifhelp findis not sufficient try typingdoc findin the command window for more details. - find the indices of all element of
Agreater than 3, store the results inidAbove3 - replace all element of
Agreater than 3, with the number 66, store inA66 - find the indices of all element of
Awhich are not equal to 2, store inidNot2
3. Two Dimensional Arrays
Operators needed: =,( ),(:)
Commands needed: randi, help
Tasks
Complete the following tasks in the supplied file problem_3.m
- use the
randicommand to create a (2 × 5) array with random numbers between [0, 10], store inA2. - extract row 1 from
A2using the colon operator, store inr1 - extract row 2 from
A2using the colon operator, store inr2 - extract column 2 from
A2using the colon operator, store inc2 - extract the third fourth and fifth columns of
A2, store inc3. Use the:operator andendkeyword (seedoc end“Access Elements of Vector” section). - replace the 1st row of
A2with the sum of its 2 rows (r1+r2) - concatenate
r1as the third row ofA2, store inA3
4. Conditions
Variable type: Boolean Logical Operators needed: ==, ||, &&, ∼= Commands needed: if, else, input, strcmp, error
Tasks
- Complete this task in the file
problem_4_1.m. Create a script which generates a random number between 0 and 10 usingrandi, and checks if the number is above 6. The script should display (disp) ”I knew It” if it is or “Maybe next time” if its not. - Complete this task in the file
problem_4_2.m. Create a script which asks the user to input a string (input). If the string is ”linear” or ”quadratic” display “thanks for selecting [user input]”, where [user input] is the string the user wrote.
If the string is not ”linear” or ”quadratic” display ‘Invalid string input detected.’as an error.
5. For Loops
Commands needed: if, for, numel
Tasks
Complete the following tasks in the supplied file problem_5.m
Using the 1D array of numbers: A = [6 8 4 2 -5 0 0 1 -4]
- use a for loop to display each element of
Aone at a time, at the same time evaluate the sum ofA, store the result inS. - using a for loop, check if each element of
Ais greater than its next element, store the indices in an array variable namedid. - use a for loop to identify the element of
Agreater than 3, and decrease their value by 1, store the result inB. - use a for loop to remove the element of
Athat are negative, store the results inA2.
6. While Loops
Commands needed: if, while, warning, numel
Tasks
- create a script in the file
problem_6_1.mto ask the user to input a string, and check if the string is ”linear” or ”quadratic”, else print a warning and ask the user again (infinitely). - Create a new script
problem_6_2.m(It will not currently exist!). Copy the code snippet below, then find and correct the error.clear;clc; i=0; while i<10 fprintf('Counting from 1 to 10, currently at %i \n',i); end - create a script in the file
problem_6_3.mto ask the user to input an initial number X between 1-100, divide this number by 2 and repeat until the number is below 1, store how many times you have to divide by 2. In the script
problem_6_4.m. Create a random array of size (10x1) made of numbers between [40 and 70] and find how many times each individual element must be divided by 2 before the results is below 1.Hint: Use a while loop nested within a for loop
7. Colon Operator and Linear spacing
Operators needed: :
Commands needed: linspace
Tasks
Complete the following tasks in the supplied file problem_7.m
- use the colon operator to create an array of all integer from 0 to 15, store in
x1 - use the colon operator to create an array of every other integer from 0 to 15, store in
x2 - use the colon operator to create an array of all integer starting from 10 to -10, store in
x3 - use the
linspacecommand to evaluate the 15 evenly spaced points between 1 and 3, store inx4
8. 2D plotting
Commands needed: pi, plot, cos, sin, close all, hold on, deg2rad
Tasks
Complete the following tasks in the supplied file problem_8.m
- calculate \(\sin(0.1\pi)\), store in
x(there is an in-built functionpi) - calculate the sin of the 45 degree angle, be careful about unit! (hint:
deg2rad) - evaluate 30 evenly spaced points between 0 and \(2\pi\), store in
x - use a for loop to evaluate the sin of the 30 values evenly spaced between 0 and \(2\pi\), using the variable
xyou just created, store the result in the arrayy - repeat the above without using a for loop (hint
sincan accept array inputs) - use the
plotcommand, to plot/create a visual representation ofyas a function ofx - use the
xlabelandylabelcommands to add labels to your figure - use the
plotcommand, to plot/create a visual representation of \(2\sin(x)\) as a function ofx(note this plot erased the previous plot) - use the
hold oncommand to plot both sin(x) and 2sin(x) on the same figure - use the
close allcommand, to close all figures