You can easily do that with a for loop that scans the three vectors in parallel.
First of all, you might want to check that these 3 vectors have the same length. Let's say x
is the vector with the x-coordinates, y
is the vector with the y-coordinates and idx
is the vector with the node numbers.
if(length(x)~=length(y) || length(x)~=length(idx) || length(y)~=length(idx))
error('Vectors must have the same length.');
end
Then you can proceed.
SelectedNodes=[];
for i=1:length(x) %or length(y) or length(idx)...they must have the same length
if(x(i)^2+y(i)^2<4)
SelectedNodes=[SelectedNodes idx(i)];
end
end
Now in SelectedNodes
you have the IDs of the nodes that lie inside your circle, to know how many nodes lie inside your circle, simply evaluate its length (length(SelectedNodes)
).
Update: As @rayryeng correctly pointed out, there is a much smarter way of doing this by using logical indexing instead of a for-loop. The logical indexing (in poor words) puts a logical 1
(true) in i
-th position if the i
-th element of a vector (or matrix) satisfies a particular condition. Otherwise there will be a logical 0
(false). By running, as suggested,
SelectedNodes=idx(x.^2+y.^2<4)
the code x.^2+y.^2<4
will return an array of the same length as x
(and y
) containing 1
s or 0
s in position i
depending on whether such element in x
and y
satisfies the circle equation. Such array will be the input of idx
and that means "select from idx
the value marked as true
". Finally, this will be the result stored in SelectedNodes
.