Splitapply using arrayfun or func with for loop

12 ビュー (過去 30 日間)
Leo
Leo 2017 年 10 月 25 日
回答済み: Andrei Bobrov 2017 年 10 月 25 日
Hi,
I have a time series of observations. Each variable is in a separate vector. I need to calculate the following formula for each entity in my dataset:
for t = 1:n
g(t+1) = g(t) * e(t+1)
end
There are different number of observations for each entity.
To calculate the g(t+1) I tried to use the arrayfun and implement it in splitapply to apply this function to each entity. It looks somewhat like that:
a = @(g,e)arrayfun(@(i){g(i) .* e(i+1)},1:n-1));
result = splitapply(a,g,e,entity);
However, the following error occurs: "Error using splitapply (line 132), Index exceeds matrix dimensions." I also tried
result = splitapply(a(x,1),g,e,entity);
however here this occurs: "Index exceeds matrix dimensions.
Error in @(i){g(i).*e(i+1)}
Error in @(g,e)arrayfun(@(i){g(i).*e(i+1)},1:n-1))
So I think that this is just not the proper way to calculate this formula for each entity. Can someone please help ? What am I doing wrong?
Thanks in advance!
  2 件のコメント
Birdman
Birdman 2017 年 10 月 25 日
If you have vectors which do not have the same size(different number of observations sentence means this), the dimension error will be inevitable.
Guillaume
Guillaume 2017 年 10 月 25 日
arrayfun is definitively the wrong tool for a recursive equation as you have. You probably need to use filter instead.
However, it's really unclear what you are to trying to achieve overall with your splitapply. Can you provide a small example of input data and what you want as output.

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 10 月 25 日
out = accumarray(entity(:),1:numel(g),[],@(x){cumprod([g(x(1));e(x(2:end))],1)});
out = cell2mat(out);

その他の回答 (0 件)

カテゴリ

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