首页 > 解决方案 > 在 C 中使用 igraph 创建关联矩阵

问题描述

我正在尝试从我生成的图表中制作一个关联矩阵:

igraph_t generateGeometricGraph(igraph_integer_t n, igraph_real_t radius){
    igraph_t G_graph;
    igraph_bool_t connected;

    // generate a connected random graph using the geometric model
    igraph_grg_game(&G_graph, n, radius, 0, 0, 0);

    igraph_is_connected(&G_graph, &connected, IGRAPH_WEAK);
    while(!connected){
        igraph_destroy(&G_graph);
        igraph_grg_game(&G_graph, n, radius, 0, 0, 0);

        igraph_is_connected(&G_graph, &connected, IGRAPH_WEAK);
    }
    return G_graph;
}

这是我的图,但我无法制作矩阵:有一个库函数可以获取关联矩阵,但它也适用于二分图。我看到有这个函数 igraph_inclist_init 可能有用,但我无法获得矩阵。谢谢您的帮助!

标签: cigraph

解决方案


顶点-边关联矩阵的构造非常简单。只需遍历所有边并为每个边添加必要的矩阵条目。

根据您需要此矩阵的原因,您可能希望为此使用稀疏矩阵数据结构。igraph 有两种稀疏矩阵类型。

为简单起见,这里我展示了一个igraph_matrix_t密集矩阵数据类型的示例。

#include <igraph.h>
#include <stdio.h>

void print_matrix(igraph_matrix_t *m, FILE *f) {
  long int i, j;
  for (i=0; i<igraph_matrix_nrow(m); i++) {
    for (j=0; j<igraph_matrix_ncol(m); j++) {
      fprintf(f, " %li", (long int)MATRIX(*m, i, j));
    }
    fprintf(f, "\n");
  }
}

int main() {
    igraph_t graph;
    igraph_integer_t vcount, ecount, i;
    igraph_matrix_t incmat;

    igraph_ring(&graph, 10, 0, 0, 0);

    vcount = igraph_vcount(&graph);
    ecount = igraph_ecount(&graph);

    /* this also sets matrix elements to zeros */
    igraph_matrix_init(&incmat, vcount, ecount);

    for (i=0; i < ecount; ++i) {
        /* we increment by one instead of set to 1 to handle self-loops */
        MATRIX(incmat, IGRAPH_FROM(&graph, i), i) += 1;
        MATRIX(incmat, IGRAPH_TO(&graph, i), i) += 1;
    }

    print_matrix(&incmat, stdout);

    igraph_matrix_destroy(&incmat);
    igraph_destroy(&graph);

    return 0;
}

推荐阅读