how can k set the initial variable of my vector

3 次查看(过去 30 天)
Hello; l set an initial value of a vector to [] neighbour_n= [];but once inside the loop neighbour_n(k)= [neighbour_n(k) j] doesnt work it returns me this message the variable n(i) appears to change size in every loop iteration within the script consider prellocating for speed My target is to get a vector of indices [1 3 5 6 ..] returned error : %
??? Attempted to access neighbour_n(1); index out of bounds because numel(neighbour_n)=0.
Error in ==> agawa at 52
neighbour_n(k)= [neighbour_n(k) j];
%
my code: %
N=200;
*neighbour_n(k)= [];*
m=0;
for k=1:N;
for j= k+1 : N;
d =((nodesX(k)-nodesX(j))^2+(nodesY(k)-nodesY(j))^2)^0.5;
if d<=200;
m=m+1; % number of created links
line([nodesX(k),nodesX(j)],[nodesY(k),nodesY(j)]);
A(k, j)=1;
neighbour_n(k)= [neighbour_n(k) j];
else
A(k, j)=0;
end;
end;
display(A(k, j));
end;
%

采纳的回答

Geoff Hayes
Geoff Hayes 2015-3-5
mazari - in the line of code
neighbour_n(k)= [neighbour_n(k) j];
you are trying to access neighbour_n(k) (for k equals one) before it has been created. I think that you are trying to compensate for this with your line of code
neighbour_n(k)= [];
which isn't quite correct in terms of syntax. As the code only updates the kth row of neighbour_n if the distance condition is met, I suspect that you want neighbour_n to be a cell array as each row can have a different number of columns (neighbours). Try initializing this array outside the for loop as
neighbour_n = cell(N,1);
and then update the kth row as
neighbour_n{k}= [neighbour_n{k} j];
Note the use of the curly braces as neighbour_n is a cell array. Try implementing the above and see what happens!
  3 个评论
Geoff Hayes
Geoff Hayes 2015-3-7
Try converting neighbour_n{k} to a string as
display(['the neighbours of ', num2str(k), ' are ', ' = ' , num2str(neighbour_n{k})]);
mazari ahmed
mazari ahmed 2015-3-8
Thanks Geoff l'm new in this community.l edit it in a another question "how to broadcast a message "hello" to all the neighbors of a node and receive a message "ACK" and how to isolate a node" . l'm also new to matlab

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by