Splitapply using arrayfun or func with for loop

10 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by