Count all pairwise interactions in a matrix
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Luis Cascao
el 23 de Abr. de 2023
Comentada: Luis Cascao
el 23 de Abr. de 2023
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
0 comentarios
Respuesta aceptada
John D'Errico
el 23 de Abr. de 2023
Editada: John D'Errico
el 23 de Abr. de 2023
If you have only one row, then it is trivial. Just use nchoosek.
Row = [2 3 5 7];
Row(nchoosek(1:4,2))
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]
[nrows,ncols] = size(Rows);
combs = nchoosek(ncols,2)
permute(reshape(Rows(:,nchoosek(1:ncols,2)),nrows,combs,2),[2 3 1])
The result is a 3-dimensional array, as it arguably should be.
As you can see, no loops were needed.
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
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!