For a function I do this (Integrate over circular range):

NIntegrate[x*y Boole[Sqrt[x^2 + y^2] < 3], {x, 1, 5}, {y, 1, 5}]

Now, I want to do the Sum of the circular set of elements in a square array.

Thanks for your 1st answers and sorry to not have been clear enough.

Example: from a two-dimensional {n, m} array mat, I would like to sum all the elements included in a circle of radius r and located at {x0, y0}.

Something like this:

Sum[mat[[n]][[m]] Boole[Sqrt[(n-x0)^2 + (m-y0)^2] < r], {n, x0-r, x0+r}, {m, y0-r, y0+r}]

Would you do it differently?

And next step, I would like to increase r up to the Sum = mySum.

I hope I'm clearer.

  • 2
    $\begingroup$ Related: mathematica.stackexchange.com/q/34827/1871 .You just need to Total@Flatten@#& after you extracting the desired elements. $\endgroup$ – xzczd Dec 9 '15 at 11:13
  • $\begingroup$ What is mySum? Is it some value you choose before-hand, and you want to find r such that the sum is equal (or at least close) to mySum? $\endgroup$ – march Dec 9 '15 at 17:11

I'm not sure I understand the question fully, but in case you meant that:

You have a square $n$ by $n$ matrix mat, and that you want to compute the sum of elements which are within a circle inscribed in the matrix, then you can do:

Total[ DiskMatrix[(n-1)/2] * mat, 2]

This assumes that n is odd so the circle can be properly centred.

References: DiskMatrix, Total


Not sure if this is what you meant. Do comment if this is not what you meant.

I would use Sum within Sum. Something like the following:

In[24]:= Sum[
  Sum[x*y Boole[Sqrt[x^2 + y^2] < 3], {x, 1, 5, 0.1}], {y, 1, 5, 

Out[24]= 6.4424

With smaller step size...

In[25]:= Sum[
  Sum[x*y Boole[Sqrt[x^2 + y^2] < 3], {x, 1, 5, 0.01}], {y, 1, 5, 

Out[25]= 6.1591

As you decrease the step size, you should see the result approaching that found by NIntegrate, namely 6.125


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.