MATLAB: For loop versus Matrix notation

accumarrayfor loop

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];

Best Answer

You can use accumarray():
Y = [uniquedates accumarray(X(:,1),X(:,2))];