Octave: How can I vectorize this function?

爱⌒轻易说出口 提交于 2019-12-13 04:00:00

问题


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.



来源:https://stackoverflow.com/questions/48273556/octave-how-can-i-vectorize-this-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!