Find array elements from condition on indices w/o loop

1 Ansicht (letzte 30 Tage)
Elliot
Elliot am 1 Nov. 2014
Beantwortet: Zoltán Csáti am 1 Nov. 2014
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)?

Antworten (1)

Zoltán Csáti
Zoltán Csáti am 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;
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);

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by