Fill matrix randomly without row-repetitions

2019-09-14 19:05发布

Please help. I'm new to matlab scripting and need a bit of help. I have a series of numbers:

A=[1 1 1 2 2 2 3 3 3 4 4 4 5]

which I want to fill randomly into an 8x12 matrix without having the same number in the same row. At the end I want all the "empty" cells of the 8x12 matrix being filled with 0's or nan.

an example could be:

result=

3 1 5 2 4 5 0 0 0 0 0 0

4 1 3 2 0 0 0 0 0 0 0 0

1 3 4 2 0 0 0 0 0 0 0 0

标签: matrix random
1条回答
▲ chillily
2楼-- · 2019-09-14 19:35
  • make sure A is sorted. A = sort(A)more info
  • make an empty matrix.
  • For each number in A: more info
    • find out how many repetitions of the number there are -> for loop in A, start is the first occurance of the number, end is the last, n = last-first+1
    • find all rows that have space for an extra number, just do a double for loop and keep track of elements that are zero
    • randomly pick n rows -> more info. To do this, make an array R of all available row indixes. Then take a random sample between 1..size(R,2) with the provided function and get all the values, you now have your row indixes.
    • randomly pick one of the empty spots in each of the selected rows and assign the number
查看更多
登录 后发表回答