MATLAB: Write a function fml(x) where given vector x returns first, middle and last. If the number of elements in the vector are even, middle should take the mean value of the innermost elements.

for loopfunctions

function [first, middle, last] = fml(x)
%FML Returns the first, middle, and last element of x
first = x(1);
last = x(length(x));
middle = x(length(x))/2;
if mod(length(x),2)==1
middle = (x(length(x)/2+1)+x(length(x)/2-1))/2;
elseif mod(length(x),2)==0
middle = x(length(x))/2;
end
——— It is not working for some reason. Getting errors at the IF sequence.

Best Answer

Hello,
Let's take a look at your code,
function [first, middle, last] = fml(x)
%FML Returns the first, middle, and last element of x
first = x(1);
last = x(length(x));
middle = x(length(x))/2;
if mod(length(x),2)==1
middle = (x(length(x)/2+1)+x(length(x)/2-1))/2;
elseif mod(length(x),2)==0
middle = x(length(x))/2;
end
Your computation of first and last seems to be good; however, there is a problem with your computation of middle. First, you don't need the line,
middle = x(length(x))/2;
as you will assign a different value to middle anyways.
Next, let's consider your code,
if mod(length(x),2)==1
middle = (x(length(x)/2+1)+x(length(x)/2-1))/2;
elseif mod(length(x),2)==0
middle = x(length(x))/2;
end
Here you are checking if the length is odd or even using modulus then determining the value of middle based on that. However, you have two problems:
1) if mod(length(x),2) == 1, we know the length is odd, meaning that,
middle = (x(ODD/2+1)+x(ODD/2-1))/2;
ODD/2 will produce a something and 1/2 result, which is not a valid index. Furthermore, if it has an odd length, then we know that it does in fact have a middle value [1 2 3] has middle value 2 for example. Try changing the line to,
middle = x(ceil(length(x)/2));
Then, when the modulus = 0, we know it's even, so try using the line,
middle = (x(length(x)/2) + x(length(x)/2+1))/2;
I hope this helps!