我不确定预分配“随机大小”,但您可以预分配大块,例如1e3
,或者对您的用例有用:
list=rand(1,x); % where x is some arbitrarily large integer
a = 1e3; % Increment of preallocation
hitlist=zeros(1,a);
k=1; % counter
for n=1:1:x
if rand(1) < list(n)
hitlist(k) = n;
k=k+1;
end
if mod(k-1,a)==0 % if a has been reached
hitlist = [hitlist zeros(1,a)]; % extend
end
end
hitlist = hitlist(1:k-1); % trim excess
% hitlist(k:end) = []; % alternative trim, but might error
list(hitlist)=[];
这不会是最快的,但至少比增加每次迭代要快得多。确保选择a
合适的;您甚至可以使用 以某种方式将其基于可用的 RAM 数量memory
,然后修剪多余的部分,这样您根本不必执行循环内的技巧。
顺便说一句:MATLAB 以列为主,因此以这种方式运行矩阵更快。即首先是第一列,然后是第二列,依此类推。对于一维数组,这无关紧要,但对于矩阵,它确实如此。因此我更喜欢使用list = rand(x,1)
, 即作为列。
对于这种特定情况,无论如何都不要使用这种循环方法,而是使用逻辑索引:
list = rand(x,1);
list = list(list<rand(size(list)));