Loop creating pairwise data structure
5 views (last 30 days)
Show older comments
Hi Everyone, I am trying to create a loop that creates this pairwise data structure in which I fill the matrix X with something like the following, for e.g. 3 people.
Person i Person j
1 2
1 3
2 3
The way I've been doing it so far is with essentially the following initial loop.
counter=1;
for i=1:200
for j=1:(i-1)
X(counter,1)=i;
X(counter,2)=j;
counter = counter+1
end
end
However no I want something like the following, where the observations are picked randomly, but then the same pairwise structure results such that all potential pairs of combinations exist. I've been playing around with this a little bit, but the results don't quite seem to be what they should.
y = randsample(unique(observations), 200)';
for assignee1=y
for assignee2=y
...
end
end
Any help would be highly appreciated!
0 Comments
Answers (1)
Deepak
on 5 Jun 2025
I understand that you are trying to generate all unique pairwise combinations from a randomly sampled list of observations (e.g., people), similar to how you previously did it deterministically using nested loops. However, now you want the order of individuals to be randomized first, and then generate all unique unordered pairs (i.e., (i, j) where i < j).
To achieve this, you can use "nchoosek" function of MATLBA after shuffling your observations.
Here is a sample MATLAB code for the same:
% Assume observations is a vector of IDs (e.g., 1:1000)
obs = unique(observations); % ensure uniqueness
y = randsample(obs, 200); % random selection of 200 unique observations
pairs = nchoosek(y, 2); % generate all unique pairs (i < j)
The result pairs is a matrix where each row contains a unique unordered pair (Person i, Person j). This method avoids nested loops and ensures all possible combinations are covered efficiently after random sampling.
Please find attached the documentataion of functions used for reference:
randsample: www.mathworks.com/help/stats/randsample.html
I hope this helps.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!