MATLAB: How can k set the initial variable of the vector

arraygraphmatrixvector

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;
%

Best Answer

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!