我想按百分比将数组拆分成段。例如,将100个元素划分为占据[1/3,1/4,5/12]
但[1/3,1/4,5/12]*100=[33.3,25,41.7]
的细分,因此需要将它们调整为整数[33,25,42]
(其他类似[34,24,42]
或{{} 1}}也可以接受,1中的徘徊并不重要。)
目前我使用循环来递归执行此操作
[33,26,41]
function x = segment(n,pct)
x = n * pct;
y = fix(x);
r = x - y;
for ii = 1 : length(r)-1
[r(ii),r(ii+1)] = deal(fix(r(ii)),r(ii+1)+r(ii)-fix(r(ii)));
end
x = y + r;
给出segment(100,[1/3,1/4,5/12])
。
没有递归循环会有更好的方法吗?
答案 0 :(得分:2)
您可以在大多数案例中使用Adiel的评论,只有在需要纠正后才能抓住并纠正任何恶意结果:
function out = segmt( n , pct )
% This works by itself in many cases
out = round(n.*pct) ;
% for the other cases:
% if the total is not equal to the initial number of point, the
% difference will be affected to the largest value (to minimize the
% percentage imbalance).
delta = sum(out) - n ;
if delta ~= 0
[~,idx] = max( out ) ;
out(idx) = out(idx) - delta ;
end