Octave: How can I vectorize this function?

2019-08-23 12:07发布

Can these for-loops of this function be vectorized?

function [sta]=bootstrap(data,N,p)
rand('state', sum(100*clock));
n=length(data);
n1=round(prctile(1:n,(100-p)/2));
n2=round(prctile(1:n,p/2+50));
for i=1:N
    choose=round(((n-1)*rand(1,n))+1);
    for j=n1:n2
        sample(j-n1+1,1)=data(choose(j));
    end
sta(i)=mean(sample);
end

1条回答
男人必须洒脱
2楼-- · 2019-08-23 12:35

Yes you can, try to replace your loop with the code below:

choose=round(((n-1)*rand(N,n))+1); sample(:,(n1:n2)-n1+1,1)=data(choose(:,n1:n2)); sta=mean(sample');

The point is you should replace i and j with the vectors you assigned for them in for block.

查看更多
登录 后发表回答