How to make a loop to find average of each month

1 回表示 (過去 30 日間)
Kristine
Kristine 2014 年 6 月 20 日
コメント済み: Kristine 2014 年 6 月 23 日
I have a data set of monthly averages and would like to make a loop to get an average of every month, so the average of every January, February, and etc.
Here is my data:
1973 1 144.46 4.68
1973 2 118.77 5.05
1973 3 57.76 7.42
1973 4 103.44 6.01
1973 5 84.11 6.18
1973 6 74.74 6.11
1973 7 64.86 6.46
1973 8 69.95 6.07
1973 9 75.25 5.66
1973 10 91.90 5.64
I can do it the hard way:
a=find(vinddata_mean_monthly(:,2)==1);
jan=vinddata_mean_monthly(a,:);
jan_dir=mean(jan(:,3));
jan_spd=mean(jan(:,4));
..
But if anyone could help my make a loop, help would be greatly appreciated.
Kristine
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 6 月 20 日
Your question is not clear
Star Strider
Star Strider 2014 年 6 月 20 日
What is the size of your matrix?
How many complete years do you have?

サインインしてコメントする。

採用された回答

dpb
dpb 2014 年 6 月 21 日
編集済み: dpb 2014 年 6 月 21 日
mndata=zeros(12,2); % preallocate
for m=1:12 % over each month
mndata(m,:)=mean(vinddata_mean_monthly(vinddata_mean_monthly(:,2)==m,3:4));
end
ADDENDUM
If the data file is regular in not having any missing months, then one can set the row indices directly and eliminate the logical addressing. Unless the size of the data file is humongous it'll likely not be of any real difference, but still...
for m=1:12
mx(m,:)=mean(vinddata_mean_monthly(m:12:end,3:4)); % take every 12th row
end
  1 件のコメント
Kristine
Kristine 2014 年 6 月 23 日
Perfect, thank you so much!

サインインしてコメントする。

その他の回答 (1 件)

Cedric
Cedric 2014 年 6 月 21 日
編集済み: Cedric 2014 年 6 月 21 日
Here is one solution if you need monthly means over all years [mean(Jan73,Jan74,..); mean(Feb73,Feb74,..); ..]:
dir_monthly = accumarray( data(:,2), data(:,3), [12,1], @mean ) ;
spd_monthly = accumarray( data(:,2), data(:,4), [12,1], @mean ) ;
where data is what you named vinddata_mean_monthly in your question. This works if there are missing data.
  2 件のコメント
dpb
dpb 2014 年 6 月 21 日
Yeah, it's that the input to accumarray must be a vector so couldn't figure out anything that wasn't either a double as you wrote or over accumarray itself that I went w/ the loop, Cedric.
Cedric
Cedric 2014 年 6 月 21 日
編集済み: Cedric 2014 年 6 月 21 日
I often test/profile the loop as well to be honest. Sometimes we think that we do better than a loop with ACCUMARRAY and we end up using CELLFUN/ARRAYFUN/etc to prepare indices because there is no way to get them drectly. And we are mistaken because it looks more elegant and concise but it is not as efficient overall.
Yet, when we are lucky enough to be in a situation where ACCUMARRAY can be used directly, it is difficult to beat.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by