MATLAB: How to calculate mean, standard deviation

table variable

Hi,
I have a table myTable that has a column called Prices (column 3). I want to calculate the mean, and std, of the log return. The code is not very nice. How to make it better? Here is my code:
myarray = myTable(:, 3)
for i = 2:size(myTable, 1)
mylog = log10(myTable{i, 3)/myTable(i-1, 3));
myarray{i-1} = mylog
end
mymean = mean(myarray)
mystd = std(myarray)
Actually, I have a set of such tables, and I will create a set of means and stds and put this set into another table. I am wondering how to do it nicely since I don't want to make many for loops. And since the amount of data is huge, I want to make the speed fast in computing.
Thank you!
Jen

Best Answer

You can index a table by the VariableNames. Furthermore we can use the properties of logs: log(a/b) = log(a) - log(b). This will allow us to utilize the diff function on the vector which will take the difference between an observation and the previous observation:
logP = log(myTable.Prices); % Takes log of all elements in the column 'Prices'
logR = diff(logP);
meanR = mean(logR);
stdR = std(logR);
Note I use the natural logarithm ( log() ) rather than base 10 ( log10() ) as this is the standard way to compute log-returns from prices. You could also combine steps 1 and 2, I just wanted to be explicit.
logR = diff(log(myTable.Prices));