For loop versus Matrix notation
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Matt Kindig
2013-1-29
Probably, but likely not in an easy-to-understand way. The fact that totals differs in size from dates complicates things.
Is there a reason you don't want to just use the for-loop?
采纳的回答
Oleg Komarov
2013-1-30
Y = [uniquedates accumarray(X(:,1),X(:,2))];
3 个评论
Oleg Komarov
2013-1-30
Map the dates to a set X in the positive N, i.e. use unique on the dates and then X(:,1) is the ia index from the call to unique.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!