Vectorize the following loop
显示 更早的评论
Hi all,
I'm trying to vectorize the following loop to speed it up
c = cumsum(weights);
A = ones(1,n);
x = rand(1,n);
for i = 1:n
j = find(c > x(i) ,1,'first');
A(i) = j;
end
where weights is an array of doubles which sum to 1 and n <= size(weights).
Any help would be grand!
B
采纳的回答
更多回答(1 个)
Sean de Wolski
2011-4-13
Note sure if it'll be faster but:
[row col] = find(bsxfun(@gt,c(:)',x(:)));
A2 = accumarray(row,col,[],@min)';
2 个评论
Matt Fig
2011-4-13
Your intuition is correct. On my machine this is 50 times slower than the simple loop, using:
A = magic(1000);
weights = A(1,:)/sum(A(1,:));
n = 1000;
Sean de Wolski
2011-4-13
It would only get slower as the matrices get bigger. I think Ben's elementary, but properly constructed, FOR-loop is probably optimal.
I just realized and am kind of surprised FIND doesn't have a dimensional argument.
类别
在 帮助中心 和 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!