3
votes

I have imported a 2Dmesh file of a surface with the mesh data into matlab.

This mesh file has 3 columns: the first one with the node number, the second one with the x-coordinate of the node and the third one with the y-coordinate of the node.

I want to select the nodes inside this circle x²+y² = 4. After importing the data file into matlab I have three column vectors, the node vector, the x-coordinate vector and the y-coordinate vector.

Any tips to impose the x² + y² < 4 condition to do this? Thank you.

1
The circle is x²+y² = 4. Inside this circle there are nodes that want to know its node number in order to set a displacement in these nodes. The nodes inside this circle may be about 100, so I would like to obtain a column vector with the number of this nodes.Anxo

1 Answers

1
votes

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 1s or 0s 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.