Calculate the mean of an array in MATLAB

891 views Asked by At

I have an array in Matlab "Numbers" that is stored in the workspace as a 400x1 double. I know how to calculate the mean of this data, but the problem I have is actually writing the code to do this. I know there are functions built-in which I could use, but I want to try and calculate this using only low-level IO commands and I'm not sure how to go about doing this. I was thinking the correct way to do this would be to create a for loop and a variable containing the total that adds each element in the array until it reaches the end of the array. With that, I could simply divide the variable 'Total' by the number of elements '400' to get the mean. The main problem I have is not knowing how to get a for loop to search through each element of my array, any help in figuring that part out is much appreciated. Thank you.

1

There are 1 answers

0
Dan Pollard On BEST ANSWER

mean(Numbers) will do it for you. If not,

sum(Numbers)/length(Numbers)

or, if you insist on not using built-in functions,

sums = 0;
counter = 0;
for val = Numbers
    sums = sums + val;
    counter = counter + 1;
end

Numbers_mean = sums/counter;

although this will almost always be slower than just calling mean.