Random elements of a vector which sum near a specific number
이전 댓글 표시
This is a fun question. I have a large vector which I need to take out 1000 random sub-vectors whose elements all add up to around the same value.
The length of this vector is 33268 with an average value of 0.028743, max of 6.0637, min of 0.006063, and std of 0.040495. The total sum is 956.23 and I need subvectors which add to 20, 30, and so on... So I think this should be possible while being fairly random. This is my attempt:
for j=1:1000
while 1
randoms = (randi(2,[1 length(parentweight)])-1);
sumweights(i) = sum(parentweight(find(randoms)));
if (sumweights>=n-mean(parentweight))&&(sumweights<=n+mean(parentweight))
break;
end
end
randsubinds{j} = randoms;
end
end
I let this run for 86000 iterations and the minimum sum was 462.19 and the max was 495.35 with a 4.5 std. In other words it seems to be always choosing almost exactly half of the elements and will never go down to around 20. That's because it's a uniform distribution I assume but there's no poisson distributed integer function.
While typing this out I came up with this:
for j=1:1000
broken = 0;
while 1
for i = 1:length(parentweight)
randoms(i) = randi(length(parentweight),1);
subweights(i) = parentweight(randoms(i));
if (sum(subweights)>=n-mean(parentweight)/2)&&(sum(subweights)<=n+mean(parentweight)/2)
broken = 1;
break;
end
end
if broken
break;
end
clear randoms subweights
end
randsubinds{j} = randoms;
clear randoms subweights
end
This is very slow. Anyone have ideas on a better way to do this?
댓글 수: 2
Jim Hokanson
2013년 7월 2일
Do you care about the uniqueness of the solutions both within a target value and between target values? For the between example would a vector of ids for 20 be fine and that same vector plus a numeric value of 10 be fine for 30 (assuming 10 were actually present). The main point being that the two vectors only differ by a small subset of numbers.
Jon
2013년 7월 2일
채택된 답변
추가 답변 (1개)
Image Analyst
2013년 7월 2일
0 개 추천
I'm not sure I understand why you think that random elements taken from a vector should ever add up to a specific number, unless they're integers and you just got lucky.
댓글 수: 2
Image Analyst
2013년 7월 2일
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!