Generate matrix of precise length and in ascending order
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello, i want to generate a matrix of elements like the following :
N = 10; M = 4; N and M are variables.
A = [1 1 1 7,
1 1 2 6,
1 1 3 5,
1 1 4 4.....]
so on and so forth.
Basically the first element should be one and rest of the elements should be in the ascending order. Also the matrix has to satisfy the row sum of N and the number of elements as specified by M.
I have used randperm, but i cannot maintain the specifed order.
Thanks for your replies.
3 comentarios
J. Alex Lee
el 3 de Feb. de 2020
I am not sure that your posted code is accomplishing your stated objective...
I'm also just seeing a pattern that I didn't see before in your example. The 3rd column has ascending values...is that a feature you want, or an accident of your example? I think your mention of randperm suggested that you want a random matrix with the following features:
- first column is always 1's
- row sums are always N
- Number of columns is fixed to M
How about number of rows? And then all of David's questions below.
Respuestas (3)
David Hill
el 3 de Feb. de 2020
What are your numbers limited to? (1-10)? Do you need all combinations? If numbers limited to 1-R and you only need some random combinations:
R=10;%numbers in maxtrix limited to 1-10
A=randi(10,[10000,M]);%the 10000 can be whatever you want but enough to generate several row sums == N
a=sum(A,2);
A=A(a==N,:);
A=sort(A,2);
A=sortrows(A,1:M);
A=unique(A,'rows');
4 comentarios
David Hill
el 3 de Feb. de 2020
Yes, but you could easily just delete all rows not starting in 1. I really don't know exactly what is wanted.
J. Alex Lee
el 3 de Feb. de 2020
This seems to work, and is less wasteful
RowSum = 10;
NCols = 4;
NRows = 70000;
A = randi(floor((RowSum-2)/(NCols-2)),[NRows,NCols-2]);
Remainder = RowSum - sum(A,2) - 1;
A = sort([ones(NRows,1),A,Remainder],2);
% test
any(RowSum~=sum(A,2))
any(A(:,1)~=1)
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!