Reputation: 661
Given a square matrix with sides of length L, how one can extract in R all the values that fall into the largest possible circle able to fill the matrix?
I found Filled circle in matrix(2D array) for C++ but how to test if the position of each cell of the matrix falls into the equation? How to know the X and Y of each cell while using an apply for exemple?
Upvotes: 3
Views: 1385
Reputation: 94182
For some 8x8 matrix m
:
m = matrix(1:64,8,8)
create a data frame of the coordinates:
g = expand.grid(1:nrow(m), 1:nrow(m))
compute distance-to-centre:
g$d2 = sqrt ((g$Var1-4.5)^2 + (g$Var2-4.5)^2)
compare with circle radius:
g$inside = g$d2<=4
you now have a data frame of row, column, distance to centre, and is-it-inside:
> head(g)
Var1 Var2 d2 inside
1 1 1 4.949747 FALSE
2 2 1 4.301163 FALSE
3 3 1 3.807887 TRUE
4 4 1 3.535534 TRUE
5 5 1 3.535534 TRUE
Then you can extract from a matrix by a two-column matrix with:
m[as.matrix(g[g$inside,c("Var1","Var2")])]
[1] 3 4 5 6 10 11 12 13 14 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
[26] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 50 51 52 53 54 55 59 60
[51] 61 62
from your image that should be 64 minus 12 (three in each corner) cells, so the length of 52 in my answer looks correct.
If you are looking for speed then skip the square root and compare with 16, the distance-squared. But you'll probably find a solution in C++ much faster.
Upvotes: 7