Count all pairwise interactions in a matrix
Mostrar comentarios más antiguos
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
Respuesta aceptada
Más respuestas (1)
LeoAiE
el 23 de Abr. de 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
1 comentario
Luis Cascao
el 23 de Abr. de 2023
Categorías
Más información sobre MATLAB en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!