generating a specific sequence block of numbers in matlab

46 views Asked by At

I need to generate a sequence of 8 blocks of numbers. The block sizes can vary between 28 and 32. The part I am stuck is that the sum of all the blocks has to be a specific number. Let's say 243.

I tried a loop block by block where the block size is randomly generated between those values, but the last block either gets to big or to small most of the time. I can keep this running until I get a few that work, but it's not that efficient.

I'm sure there's a better way. Thanks for any help Best wishes

1

There are 1 answers

0
Hein Wessels On

Calculate 8 blocks as you are doing at the moment. The sum of all these blocks will then be more, or less, than the desired sum.

Then, add all the blocks together and find actual sum. E.g:

blocks = randn(8,28);
actual_sum = sum(sum(blocks));
desired_sum = 243;

Then you calculate ratio that you must multiply all the values with to achieve the desired sum. E.g:

ratio = desired_sum/actual_sum;

Then you just multiply all your blocks with this ratio, and you will achieve your goal. E.g:

blocks = blocks * ratio;

This will result in values with decimals (or floats). If you want integers then just round all the values, and adjust the last block a little with the difference this created. E.g:

blocks = round(blocks,0);
diff = sum(sum(blocks)) - desired_sum;
blocks(1,1) = blocks(1,1) - diff;
if sum(sum(blocks))==desired_sum
    fprintf("It works!");
end

Disclaimer: I don't have Matlab with me, so you might need to fix some function names or so. The method behind it should be solid.