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

  1. store the value 6 in a variable x
  2. add two to x, store the results in the variable y
  3. multiply y by 2 and subtract half of x to it, store the results in z
  4. use the == operator to check z is equal to 13
  5. learn how to use the sqrt command: type help sqrt into the command window
  6. store the value 16 in the variable t.
  7. evaluate the remainder of t divided by 3 using the rem command (use help)
  8. use the sqrt command to calculate the square root of t and store it in x (note, this will overwrite the previous value of x)
  9. calculate the square of x using the ˆ operator, store the results in t2
  10. use the == operator to check t2 is equal to t
  11. set t=10 and repeat steps 8-10.

Spoiler alert - in step 11 you will encounter the unintuitive result that t2 does not equal t. This implies \(\sqrt{10}^2 \ne 10\), which is of course wrong. If you enter t2-t in 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 python

from math import sqrt
sqrt(10)**2-10

Therefore 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 eps to 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) and eps(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

  1. create a small 1D array (e.g. a vector), named A, containing the numbers 0, 2, 5, 8, 9
  2. replace the fourth value of A with the number 1
  3. subtract 1 to each element of A, and store the result in X

    MATLAB is case sensitive; A and a are different variables

  4. add all the values of A using the sum command, and store in s
  5. multiply each element of A by itself (i.e. element-wise multiplication), store in B
  6. take the transpose of A, store in At
  7. use the find command to find the index of element of A equal to 5, store the result in id5. If help find is not sufficient try typing doc find in the command window for more details.
  8. find the indices of all element of A greater than 3, store the results in idAbove3
  9. replace all element of A greater than 3, with the number 66, store in A66
  10. find the indices of all element of A which are not equal to 2, store in idNot2

3. Two Dimensional Arrays

Operators needed: =,( ),(:)

Commands needed: randi, help

Tasks

Complete the following tasks in the supplied file problem_3.m

  1. use the randi command to create a (2 × 5) array with random numbers between [0, 10], store in A2.
  2. extract row 1 from A2 using the colon operator, store in r1
  3. extract row 2 from A2 using the colon operator, store in r2
  4. extract column 2 from A2 using the colon operator, store in c2
  5. extract the third fourth and fifth columns of A2, store in c3. Use the : operator and end keyword (see doc end “Access Elements of Vector” section).
  6. replace the 1st row of A2 with the sum of its 2 rows (r1+r2)
  7. concatenate r1 as the third row of A2, store in A3

4. Conditions

Variable type: Boolean Logical Operators needed: ==, ||, &&, ∼= Commands needed: if, else, input, strcmp, error

Tasks

  1. Complete this task in the file problem_4_1.m. Create a script which generates a random number between 0 and 10 using randi, 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.
  2. 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]

  1. use a for loop to display each element of A one at a time, at the same time evaluate the sum of A, store the result in S.
  2. using a for loop, check if each element of A is greater than its next element, store the indices in an array variable named id.
  3. use a for loop to identify the element of A greater than 3, and decrease their value by 1, store the result in B.
  4. use a for loop to remove the element of A that are negative, store the results in A2.

6. While Loops

Commands needed: if, while, warning, numel

Tasks

  1. create a script in the file problem_6_1.m to 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).
  2. 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
    
  3. create a script in the file problem_6_3.m to 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.
  4. 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

  1. use the colon operator to create an array of all integer from 0 to 15, store in x1
  2. use the colon operator to create an array of every other integer from 0 to 15, store in x2
  3. use the colon operator to create an array of all integer starting from 10 to -10, store in x3
  4. use the linspace command to evaluate the 15 evenly spaced points between 1 and 3, store in x4

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

  1. calculate \(\sin(0.1\pi)\), store in x (there is an in-built function pi)
  2. calculate the sin of the 45 degree angle, be careful about unit! (hint: deg2rad)
  3. evaluate 30 evenly spaced points between 0 and \(2\pi\), store in x
  4. use a for loop to evaluate the sin of the 30 values evenly spaced between 0 and \(2\pi\), using the variable x you just created, store the result in the array y
  5. repeat the above without using a for loop (hint sin can accept array inputs)
  6. use the plot command, to plot/create a visual representation of y as a function of x
  7. use the xlabel and ylabel commands to add labels to your figure
  8. use the plot command, to plot/create a visual representation of \(2\sin(x)\) as a function of x (note this plot erased the previous plot)
  9. use the hold on command to plot both sin(x) and 2sin(x) on the same figure
  10. use the close all command, to close all figures

Copyright © 2025 Fintan Healy. Distributed by an MIT license.