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.
0
votes
mean(my_array) does not work?
β timko.mate
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... google.com/search?q=matlab+for
β Cris Luengo
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
1 Answers
4
votes
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
.