MATLAB Answers

For loop versus Matrix notation

1 view (last 30 days)
mutt
mutt on 29 Jan 2013
Can this be simplified to use a matrix expression instead of a for loop?:
X=[1 5.4; 1 6.3; 2 4.8; 3 7.1];
dates=X(:,1);
amounts=X(:,2);
uniquedates=unique(dates);
totals=zeros(size(uniquedates));
for d = 1:size(uniquedates,1)
totals(d,1)=sum(amounts(dates==uniquedates(d,1)));
end
Y = [uniquedates totals];
  2 Comments
mutt
mutt on 30 Jan 2013
I want to find out if there is a matrix approach which can outperform the for loop when the inputs are non-trivial

Sign in to comment.

Accepted Answer

Oleg Komarov
Oleg Komarov on 30 Jan 2013
You can use accumarray():
Y = [uniquedates accumarray(X(:,1),X(:,2))];
  3 Comments
mutt
mutt on 31 Jan 2013
This approach has delivered a 99% time saving versus the for loop.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!