索引超出数组范围top10 = idx(1:10); 。为什么出现了改错误,修改一下:% 读取节点编号和坐标 fid = fopen('node_coordinates.txt', 'r'); nodeID = fscanf(fid, '%d'); coordinates = fscanf(fid, '%f'); fclose(fid); % 将节点坐标转换为3列矩阵 coordinates = reshape(coordinates, [3, length(nodeID)]); coordinates = coordinates'; % 计算连通中心性 n = length(nodeID); C = zeros(n,1); for i = 1:n for j = 1:n if a1(i,j) == 1 C(i) = C(i) + 1/(n-1); end end end % 找出前10个重要节点 [~, idx] = sort(C, 'descend'); top10 = idx(1:10); % 输出前10个重要节点的坐标 for i = 1:10 fprintf('Node %d: (%f, %f, %f)\n', nodeID(top10(i)), coordinates(top10(i),1), coordinates(top10(i),2), coordinates(top10(i),3)); end
时间: 2023-08-23 10:03:31 浏览: 81
这个错误可能是因为节点个数不足10个,所以在执行 `idx(1:10)` 时超出了数组的范围。你可以先检查一下 `idx` 数组的大小,确保它的长度不小于10,再执行 `top10 = idx(1:10);`。
修改后的代码如下:
```
% 读取节点编号和坐标
fid = fopen('node_coordinates.txt', 'r');
nodeID = fscanf(fid, '%d');
coordinates = fscanf(fid, '%f');
fclose(fid);
% 将节点坐标转换为3列矩阵
coordinates = reshape(coordinates, [3, length(nodeID)]);
coordinates = coordinates';
% 计算连通中心性
n = length(nodeID);
C = zeros(n,1);
for i = 1:n
for j = 1:n
if a1(i,j) == 1
C(i) = C(i) + 1/(n-1);
end
end
end
% 找出前10个重要节点
[~, idx] = sort(C, 'descend');
if length(idx) >= 10
top10 = idx(1:10);
else
top10 = idx;
end
% 输出前10个重要节点的坐标
for i = 1:length(top10)
fprintf('Node %d: (%f, %f, %f)\n', nodeID(top10(i)), coordinates(top10(i),1), coordinates(top10(i),2), coordinates(top10(i),3));
end
```
阅读全文