Calculating Mean inside a loop

조회 수: 2 (최근 30일)
Subhashree
Subhashree 2011년 4월 26일
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
Subhashree
Subhashree 2011년 4월 26일
Thank you. This gives me a good start point.

댓글을 달려면 로그인하십시오.

추가 답변 (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