Speeding up loop for finding index in a large vector

3 ビュー (過去 30 日間)
Michal Szkup
Michal Szkup 2020 年 4 月 2 日
編集済み: Michal Szkup 2020 年 4 月 3 日
I am trying to speed up the following piece of code. It computes position (i.e., index) of random draws according to the CDF m. In other words, it simulates the initial position of a large number of objects where these objects have CDF m. Is there a way to speed up this loop?
% Cumulative distribution function
m = sim.m;
m_vec = m(:);
m_cum =cumsum(m_vec)';
R = rand(s.N,s.T); % random draws
% Initial distirbution
ind_ini = zeros(s.N,1);
m_cum = [0 m_cum];
for ii=1:s.N
ind_ini(ii,1) = sum(R(ii,1)>m_cum,2);
end
The issue here is that m_cum is a very large vector (1-by-1e6) and s.N is also large (>100000). I tried using find function but it was slower on my machine. Also tried vectorizing naively but then I hit the limit on the size of the machine...

採用された回答

Michal Szkup
Michal Szkup 2020 年 4 月 3 日
編集済み: Michal Szkup 2020 年 4 月 3 日
I managed to cut the time by factor of 3 following the method suggested in this answer:
For benefit of others, here is the solution:
ini=1;
for ii=1:s.N
while R(ii,1)>m_cum(ini)
ini= ini+1;
end
ind_ini(ii,1) = ini;
ini = 1;
end
This is fast enough for my puropose.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by