Hello Ezgi,
I understand that you are trying to find the tuple (i, j, k) such that all three nodes are unique and number of packets sent from node “i" to node “j” and node “i” to node “k” are non-zero.
The slow speed is the result of three nested for loops present in the code which leads to O(N^3) time complexity.
You may follow the below vectorization steps for reducing the execution time:
General Initializations:
linkswithpacket = randi([0,1], 1, N*N);
Vectorization:
packets = reshape(linkswithpacket, N, N)';
[i, j, k] = ndgrid(1:N, 1:N, 1:N);
mask_packets = (packets(sub2ind([N, N], i, j)) > 0) & (packets(sub2ind([N, N], i, k)) > 0);
mask = mask_diff_ij & mask_diff_ik & mask_diff_jk & mask_packets;
combinations_withpackets2 = [i(mask), j(mask), k(mask)];
combinations_withpackets2 = sortrows(combinations_withpackets2);
toc
Elapsed time is 0.045858 seconds.
Outputs for both the implementations can be compared by sorting the “combinations_withpackets” using “sortrows()” function.
The former time is for the looped implementation, and later one is for vectorized implementation. This reduces the execution time by a factor of 10.
You can refer to the following links for more details on “ndgrid()” and “sub2ind()”:
Also, you may find these MATLAB answers helpful, attaching them for reference: