For loop versus Matrix notation

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
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?
mutt
mutt 2013년 1월 30일
I want to find out if there is a matrix approach which can outperform the for loop when the inputs are non-trivial

댓글을 달려면 로그인하십시오.

 채택된 답변

Oleg Komarov
Oleg Komarov 2013년 1월 30일

0 개 추천

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

댓글 수: 3

mutt
mutt 2013년 1월 30일
What if the values in X(:,1) are times and therefore non-integer?
Oleg Komarov
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.
mutt
mutt 2013년 1월 31일
This approach has delivered a 99% time saving versus the for loop.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2013년 1월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by