错误使用 randperm 输入必须为非负标量整数。 出错 oooo (line 709) gateway1 = randperm(gateway1, n_gateway)如何修改if file ~= -1 % 确认文件已经被正确打开 data = textscan(file, '(%f,%f,%f) to (%f,%f,%f)\n'); gateway1 = []; gateway2 = []; for i = 1:size(data{1}, 1) x1 = data{1}(i); y1 = data{2}(i); z1 = data{3}(i); x2 = data{4}(i); y2 = data{5}(i); z2 = data{6}(i); gateway1 = [gateway1; x1, y1, z1]; gateway2 = [gateway2; x2, y2, z2]; end fclose(file); % 记得关闭文件 else disp('Error: file not found or could not be opened.'); end gateway1 = randperm(gateway1, n_gateway); gateway2 = randperm(gateway2, n_gateway); state1(gateway1) = randi([0, 3], n_gateway, 1); state2(gateway2) = randi([0, 3], n_gateway, 1);
时间: 2023-12-20 09:05:28 浏览: 63
遗传算法MATLAB完整代码(不用工具箱)_tiredx1m_matlab_
randperm函数的输入参数应该是一个正整数,而不是一个向量。因此,您需要将randperm函数的输入参数修改为向量的长度。
修改代码如下:
```
if file ~= -1 % 确认文件已经被正确打开
data = textscan(file, '(%f,%f,%f) to (%f,%f,%f)\n');
gateway1 = [];
gateway2 = [];
for i = 1:size(data{1}, 1)
x1 = data{1}(i);
y1 = data{2}(i);
z1 = data{3}(i);
x2 = data{4}(i);
y2 = data{5}(i);
z2 = data{6}(i);
gateway1 = [gateway1; x1, y1, z1];
gateway2 = [gateway2; x2, y2, z2];
end
fclose(file); % 记得关闭文件
else
disp('Error: file not found or could not be opened.');
end
% 使用randperm函数随机选择n_gateway个网关
n_gateway = min(n_gateway, size(gateway1, 1));
idx = randperm(size(gateway1, 1), n_gateway);
gateway1 = gateway1(idx, :);
gateway2 = gateway2(idx, :);
state1(gateway1) = randi([0, 3], n_gateway, 1);
state2(gateway2) = randi([0, 3], n_gateway, 1);
```
在这个修改后的代码中,我们使用randperm函数中的第二个输入参数来指定要选择的元素数量。我们还添加了一个检查,以确保选择的元素数量不超过可用元素的数量。
阅读全文