Find array elements from condition on indices w/o loop

조회 수: 1 (최근 30일)
Elliot
Elliot 2014년 11월 1일
답변: Zoltán Csáti 2014년 11월 1일
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)?

답변 (1개)

Zoltán Csáti
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;
And now, index the available x and y coordinates of the grid using logical indexing:
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);

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by