Find array elements from condition on indices w/o loop
2 views (last 30 days)
Show older comments
Say I have a 2D array A. Treating the array as a geometric plane, I would now like to extract elements of A which lie a specified region such as a circle.
That is, I would like to find those elements A(i,j) such that sqrt((i-c_i)^2+(j-c_j)^2) < r, where (c_i, c_j) and r give the center and radius of the circle, respectively, and then convert these elements into a vector.
How would I do this without loops?
More generally, how can I extract elements from an array from a condition on the indices of the array (instead of the values of the array)?
0 Comments
Answers (1)
Zoltán Csáti
on 1 Nov 2014
If you regard A as the points on a plain, than you have the x and y coordinates of those specific points stored for example in matrices X and Y. If you want to make a rectangular grid, you can do that like this:
[X Y] = meshgrid(-10:1:10,-10:1:10); % matrices from the x and y coordinates
Now give the center and radius of the circle, e.g.
xCenter = 3; yCenter = 4; radius = 2;
Finally, find all those indices that fulfil the requirement:
inCircle = (xCenter-X).^2 + (yCenter-Y).^2 < radius^2;
x = X(inCircle);
y = Y(inCircle);
Then you get the corresponding pair of points in vectors x and y. You may display the structure of matrix of the required indices with
spy(inCircle);
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!