Splitapply using arrayfun or func with for loop

6 views (last 30 days)
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 Comments
Birdman
Birdman on 25 Oct 2017
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 on 25 Oct 2017
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.

Sign in to comment.

Accepted Answer

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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!