-2

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.

这个问题是这个问题的后续。

4

1 回答 1

1

如果您想为每个节点分配一个“能量”值,您可以修改我之前回答中的代码:

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);
于 2009-12-13T17:45:48.980 回答