6 Functions [10 marks]

Create a function that given a vector v returns the middle element of v. If v has an odd number of elements, then your function should return the middle element of the vector. For example, if v has the values:

1, 2, 3, 4, 5

then your function should return the value 3 (the middle element).

If v has an even number of elements, then your function should return the average of the two elements in the middle of the vector. For example, if v has the values:

1, 2, 3, 4

then your function should return 2.5 (the average of the two middle elements 2 and 3).

Your function should satisfy the following constraints:

  1. it should be named middle
  2. it should return one value y (the value of the middle element of the vector if the vector has an odd number of elements, or the average of the two values in the middle of the vector if the vector has an even number of elements)
  3. it should have one input vector value v

A solution exists that does not require an if statement, but you may use an if statement if you wish. You may use the MATLAB function mean if you wish, but there is no advantage to doing so.

Your solution should work for any vector v of one or more numeric values.

You receive part marks if your solution works only if v has an odd number of elements.

6.1 Hint

Compute the indices of the two elements that should be averaged. If v has an odd number of elements then the two elements will have the same index (so when you compute the average of the two values you just get the middle element).

6.2 Example usage

The two examples above can be computed as:

v = [1 2 3 4 5];
y = middle(v);

v = [1 2 3 4];
y = middle(v);