0

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.

JamesW
  • 43
  • 4
  • mean(my_array) does not work? – timko.mate Dec 09 '20 at 14:53
  • 1
    There are literally thousands if not millions of examples of this online. It’s so much easier to find one of those than to ask a question here... https://www.google.com/search?q=matlab+for – Cris Luengo Dec 09 '20 at 14:55
  • mean(my_array) is not calculating the mean myself using low-level IO commands. I asked the question because all the examples I found just point to using a built-in function, but sure it's fine. – JamesW Dec 09 '20 at 15:02

1 Answers1

4

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.

Dan Pollard
  • 378
  • 2
  • 12