MATLAB: Product of two graphs in MATLAB

cartesian productedge-weightedgraphgraph theorygraphsnode-weighted

I have two undirected graphs G1 and G2, they are both node and -edge weighted graphs. I want to create a graph G which is the Cartesian product of G1 and G2. G1 has 4 nodes and G2 has 15 nodes. How can I do this using MATLAB?

Best Answer

Without weights, you can compute the graph product quite quickly:
A1 = adjacency(G1);
A2 = adjacency(G2);
I1 = speye(numnodes(G1));
I2 = speye(numnodes(G2));
Aprod = kron(A1, I2) + kron(I1, A2);
Gprod = graph(Aprod);
With weights, you need to construct the weighted adjacency matrix, which unfortunately is a bit cumbersome:
>> [i, j] = findedge(G1);
>> A1 = sparse(i, j, G1.Edges.Weight, numnodes(G1), numnodes(G1));
>> [i, j] = findedge(G2);
>> A2 = sparse(i, j, G2.Edges.Weight, numnodes(G2), numnodes(G2));
>> I1 = speye(numnodes(G1));
>> I2 = speye(numnodes(G2));
>> Aprod = kron(A1, I2) + kron(I1, A2);
>> Gprod = graph(Aprod, 'upper');
The node weights should be simpler again, but I'm not sure how you would want to treat these: Is the weight of a node representing the product of node i from G1 and node j from G2 going to be the product of these node's weights, or the sum?