Count all pairwise interactions in a matrix

2 views (last 30 days)
Suppose I have the following matrix:
[23 51 42; 42 23 18]
how can I count all pairwise terms occurring per row where order is not important? In this case, for row 1 the pairwise terms are (23,51),(23,42),(42,51) and for the second row (23,42),(18,42),(18,23).
Therefore the answer is:
{(23,51),1}, {(23,42),2}, {(42,51),1}, {(18,42),1}, {(18,23),1}
Many thanks

Accepted Answer

John D'Errico
John D'Errico on 23 Apr 2023
Edited: John D'Errico on 23 Apr 2023
If you have only one row, then it is trivial. Just use nchoosek.
Row = [2 3 5 7];
Row(nchoosek(1:4,2))
ans = 6×2
2 3 2 5 2 7 3 5 3 7 5 7
But you have multiple rows. We can still use nchoosek. But now we need to be a little more creative. For example:
Rows = [1 2 4 8;2 3 5 7]
Rows = 2×4
1 2 4 8 2 3 5 7
[nrows,ncols] = size(Rows);
combs = nchoosek(ncols,2)
combs = 6
permute(reshape(Rows(:,nchoosek(1:ncols,2)),nrows,combs,2),[2 3 1])
ans =
ans(:,:,1) = 1 2 1 4 1 8 2 4 2 8 4 8 ans(:,:,2) = 2 3 2 5 2 7 3 5 3 7 5 7
The result is a 3-dimensional array, as it arguably should be.
As you can see, no loops were needed.

More Answers (1)

LeoAiE
LeoAiE on 23 Apr 2023
Hi,
great question! Here is my attempt to solve this problem and if you find it helpful please accept the answer.. Thanks
% Input matrix
matrix = [23 51 42; 42 23 18];
% Number of rows
nrows = size(matrix, 1);
% Initialize an empty cell array to store the result
pairwise_terms = {};
% Iterate through each row
for row = 1:nrows
% Get all unique pairs in the current row
pairs = nchoosek(matrix(row, :), 2);
% Iterate through each pair
for i = 1:size(pairs, 1)
% Sort the pair to ignore order
sorted_pair = sort(pairs(i, :));
if isempty(pairwise_terms)
% If pairwise_terms is empty, add the first pair with a count of 1
pairwise_terms(end + 1, :) = {sorted_pair, 1};
else
% Create a logical index array to check if the sorted_pair exists in pairwise_terms
logical_index = cellfun(@(x) isequal(x, sorted_pair), pairwise_terms(:, 1));
% Find the index of the existing pair in pairwise_terms
idx = find(logical_index, 1);
if isempty(idx)
% If the pair does not exist, add it to pairwise_terms with a count of 1
pairwise_terms(end + 1, :) = {sorted_pair, 1};
else
% If the pair exists, increment the count
pairwise_terms{idx, 2} = pairwise_terms{idx, 2} + 1;
end
end
end
end
% Display the result
pairwise_terms

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!