c - 在 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 可能有用,但我无法获得矩阵。谢谢您的帮助!
解决方案
顶点-边关联矩阵的构造非常简单。只需遍历所有边并为每个边添加必要的矩阵条目。
根据您需要此矩阵的原因,您可能希望为此使用稀疏矩阵数据结构。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;
}
推荐阅读
- python - discord.ext.commands.errors.MissingRequiredArgument:用户是缺少的必需参数。帮助 :(
- ansible - 模板化字符串时出现ansible模板错误:没有名为“产品”的过滤器
- javascript - 默认情况下以编程方式固定 chrome 扩展图标
- javascript - 无法在 ReactJs 中的服务器上使用 editorState 为 DraftJs 更新状态
- python-3.x - 从 4 个一维数组创建一个 numpy 元组矩阵
- wordpress - 重定向到移动设备的不同页面在结帐页面上不起作用
- python - 使用 pytorch 数据加载器的开始和结束在 zarr 数组上创建生成器
- c# - 自定义控件动态更新文本属性
- android - 一次 EditText 单击后显示 DatePickerDialog 和 TimePickerDialog
- javascript - foreach 不适用于由 getElementsByTagName 创建的数组