Sum of random numbers to certain value for each row in Matlab?

3 views (last 30 days)
I would like to generate random numbers (non-decimal numbers) between range 3 and 5 (numbers can repeat within this range) to add up to a certain value lets say 48. I tried the following coding and it is working fine. I have a total of 14 values (columns) for one single entry (row).
clear all
while true
A=randi([3 5],1,14);
if(sum(A)==48)
break;
end
end
disp(A)
disp(sum(A))
The above data value of 48 is for a single entry. I have around a total of 39 entries each having its own summation value whereas the other constraints are same.
How can I define summation for each entry (row) and then get the summation of the random numbers of each row equal to that value? In the current coding if I increase the number of rows then summation does not work.
If possible, How may I let MATLAB randomly choose the summation values for all 39 entries between 40 and 70 and then distribute the sum of each row (entry) to that particular corresponding sum value?
  1 Comment
Walter Roberson
Walter Roberson on 9 Mar 2022
Are you trying to create random partitions (with a fixed number of bins)?

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 9 Mar 2022
Assign all 3 to each column.
For each row, if you have not reached the total for the row yet, determine the columns of the row which are 3 or 4. Pick one of them at random. Increment that column.
  1 Comment
Walter Roberson
Walter Roberson on 9 Mar 2022
Assign all 3 to each column.
Create a vector that contains 1 to the number of columns, repeated (so two instances of each number). That will be length 2*ncol. For each row, create a random permutation of length 2*ncol. Use it to index the vector that has 1:ncol repeated, so each row is a random permutation of the numbers 1:ncol with one duplicate each.
Now for each row, calculate desired total for the row, minus 3*ncol. Then for each row take that many entries from the front of the permutation of duplicate copies of 1:ncol. Each entry indicates a column to increment by 1.
No column can get incremented more than 2 because no column number is repeated more than once in the list. So no column can end up more than 5. By chance depending on the arrangement of the permutation, some columns might not get incremented at all and will remain 3.
I think it just might be possible to vectorize everything by using a small trick involving an extra column, and accumarray, but the overhead temporary vectors might not be worth it; might be easier to do the final increments per-row.

Sign in to comment.

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!