How can I distribute certain number among rows in a way that sum of the column is equal to that number?

I have 36 areas and total supply=600. I want to distribute 600 randomly among areas but at the end sum of all those random numbers should be equal to 600 and each area must have integer number. My code doesnt work for all numbers. For example, it works for 100 but not for 1000, it takes too long to find right combination. Does anyone have an idea how to make this code better so it can work for all numbers? or do you have any better solution for this problem? Thanks
function supply_by_area=supply(num_areas,tot_dem)
areas=zeros(num_areas,2);
areas(:,1)=1:num_areas;
max_dem_for_a_area=ceil(tot_num_dem/num_areas)+2;
while 1
areas(:,2)=randi([0 max_dem_for_a_area],num_areas,1);
if sum(areas(:,2))==tot_num_dem
areas
break
end
end

 Accepted Answer

Start with 600 available. Loop over the areas except the last. For each area, generate a random integer between 0 and the number of available items and subtract that number from the available items before going on to the next. At the end, whatever items are left over go into the last area.

More Answers (1)

Use unidrnd(600/2,1,areas) to generate the random numbers 600/2 is mean value of 600.
Be aware that you want to fit random numbers to a fixed sum, which is not random.
The pragmatic solution is to modify the last component of the output of unidrnd(N/2,1,areas) to match the sum:
v=unidrnd(N/2,1,areas) correction=N-sum(unidrnd(N/2,1,areas)) v(end)=v(end)+correction
John

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!