Save results from for loop and array function

I created a function that reads a text file that has rows by year and columns with different values, converts it to an array, and finds annual mean values.
I'd like to use a for loop (or any loop) that will create the mean for each year, without me having to copy and paste the function with a new year input value each time.
I would then like to save each iteration into a table or an array, such that each row is for each year and includes multiple/separate columns from the function.
My function works for one year at a time, saving the results into an array. The for loop only saves the last year into a table.
Can you please recommend how to improve the for loop?
load file.txt
for year=2009:2016
Amean = annmean_dmean(year);
Atable = table(year, Amean);
end
function [annmean_year]= annmean_dmean (year)
T = readtable('file.txt');
A =table2array(T);
id = A(:,1)==year;
dmean_year = A(id,:);
annmean_year = mean(dmean_year(:,3:end),'omitnan');
end

2 件のコメント

Andrei Bobrov
Andrei Bobrov 2017 年 10 月 26 日
Please attach your file.txt.
kathy
kathy 2017 年 10 月 26 日
This is a condensed version.

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

 採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 10 月 26 日
編集済み: Andrei Bobrov 2017 年 10 月 26 日

0 投票

T = readtable('file.txt');
A = varfun(@(x)mean(x,'omitnan'),T,'Group',1)
out = A(:,[1,4:end]);

1 件のコメント

kathy
kathy 2017 年 10 月 26 日
That's amazing! Thanks!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

2017 年 10 月 26 日

コメント済み:

2017 年 10 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by