MATLAB Answers

fill matrix with all options of successive, increasing numbers 1-5

61 views (last 30 days)
I want to construct a matrix, m x n, filled with the numbers 1 till 5. The numbers have to be successive, and have to be increasing. One column of the matrix could for example look like.
A =1 1 2 2 2 2 3 4 5 5 5 5
or
A = 1 2 3 3 3 4 5 5 5 5 5 5
I want to construct a matrix with all possible options. The first column of matrix A therefore should look like this:
A(:,1) = 1 1 1 1 1 1 1 1 2 3 4 5
and the last one like this
A(:,end)= 1 2 3 4 5 5 5 5 5 5 5
In my case, the matrix will have a length of 96, instead of the above example where the length is 12. Could you help me?

  8 Comments

Show 5 older comments
Sjoukje de Lange
Sjoukje de Lange on 25 Jan 2021
yes correct. I need to divide an area of 96 kilometer in 5 parts, in the most optimal way (optimal being defined by the values of certain parameters). I need this matrix to define all possible options to divide it. Unfortunatly something like cluster analysis to divide it won't be possible with my data since there are multiple (in)dependend variables, so we came up with this solution. Now the question is: how to tell the computer... :)
Adam Danz
Adam Danz on 25 Jan 2021
Why do you need repeated values, then?
There are 61,124,064 ways to select 5 items out of 96 and that's without repetition. With the repetitions you're looking at billions.
Addendum: the number above includes indicies that increase and decrease. If you're only interested in increading indicies, that number will be reduced.
Sjoukje de Lange
Sjoukje de Lange on 25 Jan 2021
Hmmm that might be a but extreme yeah... I need repeating values because I want to label each parameter at each kilometer with number 1-5.

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 25 Jan 2021
Edited: Bruno Luong on 25 Jan 2021
p = 5;
n = 12;
j = nchoosek(2:n,p-1);
m = size(j,1); % == nchoosek(n-1,p-1) == 330 and not 96
i = repmat((1:m)',1,p-1);
A = cumsum(accumarray([i(:) j(:)],1,[m n]),2)+1

  4 Comments

Show 1 older comment
Sjoukje de Lange
Sjoukje de Lange on 25 Jan 2021
will try tomorrow (it's damn late here now... :) ), will let you know! thanks for helping!
Adam Danz
Adam Danz on 25 Jan 2021
Nice one (+1)
When n==96, A has 3,183,545 rows and takes less than 3 sec using the same machine as above.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!