Octave: How can I vectorize this function?

2019-08-23 11:43发布

问题:

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:

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.