Matlab: need some help for a seemingly simple vectorization of an operation

后端 未结 3 777
孤独总比滥情好
孤独总比滥情好 2020-12-19 21:12

I would like to optimize this piece of Matlab code but so far I have failed. I have tried different combinations of repmat and sums and cumsums, but all my attempts seem to

3条回答
  •  猫巷女王i
    2020-12-19 21:35

    The nchoosek(v,k) function generates all combinations of the elements in v taken k at a time. We can use this to generate all possible pairs of indicies then use this to vectorize the loops. It appears that in this case the vectorization doesn't actually improve performance (at least on my machine with 2017a). Maybe someone will come up with a more efficient approach.

    idx = nchoosek(1:T,2);
    d = bsxfun(@minus,(X(idx(:,2),:) - X(idx(:,1),:)), (idx(:,2)-idx(:,1))/T);
    Result = sum(abs(d),1)';
    

提交回复
热议问题