How do I solve the "friendship" problem, i.e., transform a 2D friendship/logical array into n dimensions without using loops?
Show older comments
Hi All,
I'm going to call this a "friendship" problem. I want to find friendship groups. I can set up a 2D logical array with each "person" reflected as both a row and column. For example, person 1 is reflected in both row 1 and column 1, person 2 in row 2 and column 2, etc. If the two people are friends, then cells at the intersections of their respective rows/columns are set to true, otherwise the values are false. In this example, people cannot be friends with themselves. Here's an example array:
n = 10; % number of people
friends = false(n, n); % set up logical array
friends(1,2) = true; % 1 and 2 are friends
friends(2,1) = true; % 1 and 2 are friends
friends(3,4) = true; % 3 and 4 are friends
friends(4,3) = true; % 3 and 4 are friends
friends(3,5) = true; % 3 and 5 are friends
friends(5,3) = true; % 3 and 5 are friends
friends(4,5) = true; % 4 and 5 are friends
friends(5,4) = true; % 4 and 5 are friends
So, 1 and 2 are only friends with each other, whereas 3, 4 and 5 form a group of 3 friends. We can search through the logical array to find the group by storing the results in the next dimension:
friends3 = false(n,n,n); % set up 3D logical array
for F1 = 1:n
for F2 = 1:n
for F3 = 1:n
if friends2(F1,F2) == true && ... % 1 is friends with 2
friends2(F1,F3) == true && ... % 1 is friends with 3
friends2(F2,F3) == true % 2 is friends with 3
friends3(F1,F2,F3) = true;
end
end
end
end
[F1, F2, F3] = ind2sub( size(friends3), find(friends3) ); % find group of 3 friends
group3 = [F1 F2 F3]; % store the results
% ----- deal with repeats to return the group only once
for G = 1:size(group3,1)
group3(R,:) = sort(group3(G,:));
end
group3 = unique(group3, 'rows')
We can look for groups of 4 friends using the same method:
friends4 = false(n,n,n,n); % set up 3D logical array to look for groups of 4
for F1 = 1:n
for F2 = 1:n
for F3 = 1:n
for F4 = 1:n
if friends2(F1,F2) == true && ... % 1 is friends with 2
friends2(F1,F3) == true && ... % 1 is friends with 3
friends2(F2,F3) == true && ... % 2 is friends with 3
friends2(F1,F4) == true && ... % 1 is friends with 4
friends2(F2,F4) == true && ... % 2 is friends with 4
friends2(F3,F4) == true % 3 is friends with 4
friends4(F1,F2,F3,F4) = true;
end
end
end
end
end
sum(sum(sum(sum(friends4)))) % there are no matches in this case!
As should be clear, this method becomes extremely inefficient when searching for large groups of friends. Is a better way to extend by 2D friendship matrix into n dimensions without using loops?
Thanks!
D.
Answers (0)
Categories
Find more on Annotations 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!