Calculating Mean inside a loop

2 次查看(过去 30 天)
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

采纳的回答

Matt Tearle
Matt Tearle 2011-4-26
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.

更多回答(1 个)

Matt Fig
Matt Fig 2011-4-26
Use HISTC for binning problems. See both the one and two output functionality.

类别

Help CenterFile Exchange 中查找有关 Probability Distributions and Hypothesis Tests 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by