-1

たとえば、次のコードは、ランダムに生成されたノードn=5のプロットを示します。nこれらのノードは構造ではありません (単にプロットされた点) が、すべてのノードに同じようにメッセージを割り当て、ノードの ID と位置を追跡したいsinkと考えています。source

たとえば、node 4(x,y) 座標がある場合、andも(.3452 , .5463)割り当てたいと思います。これどうやってするの?node 4msgtemp_value

コード:

n = input('No. of Nodes:');

sink = [0 0];
source = [1 1];

node = rand(n,2)
x = node(:,1);
y = node(:,2);

x1 = sink(:,1);
y1 = sink(:,1);

x2 = source(:,1);    
y2 = source(:,1);

plot(x,y,'o')
hold on

plot(x1,y1,'r*')
hold on

plot(x2,y2,'r*')
hold on

sink = struct;    
sink.msg = 'temp';
sink.temp_value = '30'

source = struct;
source.msg = 'temp';
source.temp_value = '30'
4

1 に答える 1

4

各「ノード」に関連付けられたすべてのデータを格納する構造体の配列を作成することをお勧めします。次の方法で、STRUCTを 1 回呼び出すだけで、ノードのすべてのデータを作成できます。

N = 5;                         %# 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
               'message','temp',...  %# Assign default message
               'value',30);          %# Assign default value

変数nodesは、フィールド、、、およびをもつN 行 1 列の構造体配列です。通常の配列とフィールドのインデックス付けを使用して、データにアクセスして変更できます。xymessagevalue

>> nodes(1)  %# Contents of node 1

ans = 

          x: 0.4387
          y: 0.4898
    message: 'temp'
      value: 30

>> nodes(1).message  %# Message for node 1

ans =

temp

>> nodes(1).message = 'hello world!';  %# Change message for node 1

次に、次の方法でノードをプロットできます。

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
于 2009-12-11T20:27:51.853 に答える