for i = 1:10 node_id = idx(top10_idx(i)); % 使用排序后的索引来获取节点编号 node_bc = BC2(node_id); node_x = node_pos(top10_idx(i), 1); % 使用未排序的索引来获取节点坐标 node_y = node_pos(top10_idx(i), 2); % fprintf('节点 %d,介数中心性为 %f,坐标为 (%f,%f)\n', node_id, node_bc, node_x, node_y); end怎么把最后出来的结果保存在txt文件中
时间: 2024-02-12 07:03:28 浏览: 22
您可以在循环过程中,将每次输出的结果保存到一个字符串中,最后再将该字符串保存到txt文件中。具体步骤如下:
1. 定义一个空字符串,用于保存结果。
2. 在循环中,使用fprintf()函数将结果输出到命令行,并使用sprintf()函数将结果转换为字符串形式。
3. 将步骤2中得到的字符串添加到步骤1中定义的字符串末尾。
4. 循环结束后,使用Python的文件操作将步骤1中保存的字符串写入txt文件中。
以下是一个示例代码,将每个节点的介数中心性和坐标保存到名为“result.txt”的文件中:
```
result = '' % 定义一个空字符串
for i = 1:10
node_id = idx(top10_idx(i));
node_bc = BC2(node_id);
node_x = node_pos(top10_idx(i), 1);
node_y = node_pos(top10_idx(i), 2);
% 输出结果到命令行
fprintf('节点 %d,介数中心性为 %f,坐标为 (%f,%f)\n', node_id, node_bc, node_x, node_y);
% 将结果转换为字符串并添加到result字符串末尾
result = sprintf('%s节点 %d,介数中心性为 %f,坐标为 (%f,%f)\n', result, node_id, node_bc, node_x, node_y);
end
% 将result字符串保存到txt文件中
fid = fopen('result.txt', 'w');
fprintf(fid, '%s', result);
fclose(fid);
```
注意,在使用完文件后,一定要关闭文件,否则可能会导致文件损坏或其他问题。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)