Find array elements from condition on indices w/o loop
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Zoltán Csáti
2014-11-1
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!