poster
2019-12-10, 16:49
在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. 这个问题是遵循了这个问题 (https://stackoverflow.com/questions/1889522/problem-related-to-stucture-and-non-structure-in-matlab) 。
回答:
如果要为每个节点分配“能量”值,则可以修改我先前的回答中 (https://stackoverflow.com/questions/1889522/problem-related-to-stucture-and-non-structure-in-matlab/1890672#1890672)的代码:
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 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/max.html)函数找到能量最大的节点:
[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);
更多&回答... (https://stackoverflow.com/questions/1897028)
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. 这个问题是遵循了这个问题 (https://stackoverflow.com/questions/1889522/problem-related-to-stucture-and-non-structure-in-matlab) 。
回答:
如果要为每个节点分配“能量”值,则可以修改我先前的回答中 (https://stackoverflow.com/questions/1889522/problem-related-to-stucture-and-non-structure-in-matlab/1890672#1890672)的代码:
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 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/max.html)函数找到能量最大的节点:
[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);
更多&回答... (https://stackoverflow.com/questions/1897028)