Reputation: 876
I want to create a matrix like
[1 2;
1 3;
1 4;
1 5;
2 3;
2 4;
2 5;
3 4;
3 5;
4 5 ]
when the size is 5. I aim to have sizes greater than 100. How can I create a matrix like this using vertorization in MATLAB?
Upvotes: 3
Views: 107
Reputation: 32920
You're looking for binomial coefficients, so use the built-in nchoosek
command. For example, the matrix in your question can be generated by:
A = nchoosek(1:5, 2)
This results in:
A =
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Upvotes: 7
Reputation: 19870
One solution:
[r,c]=find(tril(ones(N),-1));
result = [c,r];
As a bonus, you can get the number of rows in such matrix with
nrows = nchoosek(N,2);
Upvotes: 2