Calculating Mean inside a loop
2 views (last 30 days)
Show older comments
Hi,
I am new to matlab and am struggling with a very simple problem that I cannot solve. I have a set of data that needs to be binned by temperature. Once I have them in bins, I need to calculate the mean and std dev. of variables. I wrote the following code but it does not work i.e. does not give me the correct mean and std dev. Any help will be greatly appreciated.
for i = 1:59
if(T(i)>-30. && T(i)<=-25.)
MnT30 = Mean(T(i)); SnT30 = std(T(i));
MnIWC30 = Mean(IWC(i)); SnIWC30 = std(IWC(i));
MnDe30 = Mean(De(i)); SnDe30 = std(De(i));
MnVm30 = Mean(Vm(i)); SnVm30 = std(Vm(i));
elseif(T(i)>-35 && T(i)<=-30.)
MnT35 = Mean(T(i)); SnT35 = std(T(i));
MnIWC35 = Mean(IWC(i)); SnIWC35 = std(IWC(i));
MnDe35 = Mean(De(i)); SnDe35 = std(De(i));
MnVm35 = Mean(Vm(i)); SnVm35 = std(Vm(i));
end
end
0 Comments
Accepted Answer
Matt Tearle
on 26 Apr 2011
If you have Statistics Toolbox, you can use grpstats. In general, if you're doing a lot with variables in groups, you might want to make a categorical grouping array:
T = randi(100,300,1); % some fake data
levels = [-Inf,20,35,60,80,Inf];
Tgrp = ordinal(T,num2str((1:(length(levels)-1))'),[],levels);
or, simply, as Matt Fig suggests, use histc to bin:
[~,Tgrp] = histc(T,levels);
Then
[m,s]=grpstats(T,Tgrp,{@mean,@std})
gives you the mean and std dev of each group in the vectors m and s, respectively.
More Answers (1)
See Also
Categories
Find more on Probability Distributions and Hypothesis Tests in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!