Search code examples
arraysmatlabmatlab-struct

how to assign random energy E to every node and compare two nodes for maximum energy and also find distance between them?


As helped by gnovice I got following code, but now I want to assign energy (randomly) to every nodes using E=floor(rand(1)*10) and also want to compare for maximum energy and what is distance between them?

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.

this question is follow up of this question.


Solution

  • If you want to assign a value for "energy" to every node, you can modify the code from my previous answer:

    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
    

    You can find the node with maximum energy using the MAX function:

    [maxValue,maxIndex] = max([nodes.energy]);
    

    and you can find the distance between a pair of nodes in the following way:

    index = [1 3];  %# Compare nodes 1 and 3
    dist = sqrt(diff([nodes(index).x])^2+diff([nodes(index).y])^2);