在
gnovice的帮助下,我得到了以下代码,但是现在我想使用E=floor(rand(1)*10) (随机)为每个节点分配能量,并且还想比较最大能量以及它们之间的距离是多少?
N=input('no. of nodes : '); %# Number of nodes coords = num2cell(rand(N,2)) %# Cell array of random x and y coordinates nodes=struct('x',coords(:,1),... %# Assign x coordinates 'y',coords(:,2)); %# Assign y coordinates plot([nodes.x],[nodes.y],'r*'); %# Plot all the nodes in red index = randi(N,[1 2]) %# Pick two nodes at random hold on; plot([nodes(index).x],[nodes(index).y],'b*'); %# Plot 2 random nodes in blue index(1) %# which node is selected first. index(2) %# which node is selected second. 这个问题是遵循了
这个问题 。
回答:
如果要为每个节点分配“能量”值,则可以修改
我先前的回答中的代码:
N = input('no. of nodes : '); %# Number of nodes coords = num2cell(rand(N,2)); %# Cell array of random x and y coordinates E = num2cell(ceil(10*rand(N,1))); %# Cell array of random integers from 1 to 10 nodes = struct('x',coords(:,1),... %# Assign x coordinates 'y',coords(:,2),... %# Assign y coordinates 'energy',E); %# Assign energy 您可以使用
MAX函数找到能量最大的节点:
[maxValue,maxIndex] = max([nodes.energy]); 您可以通过以下方式找到一对节点之间的距离:
index = [1 3]; %# Compare nodes 1 and 3 dist = sqrt(diff([nodes(index).x])^2+diff([nodes(index).y])^2);
更多&回答...