# Passing a loop index value into NIntegrate

I would like to use the NIntegrate[] function to calculate an integral within a Do[] Loop, and pass in the value of the index into the integrand.

As a simple, hypothetical example I would like to calculate the following integrals:

$C_1[T]$= $\int_0^1 \frac{T}1 dx$

$C_2[T]$= $\int_0^1 \frac{T}2 dx$

$C_3[T]$= $\int_0^1 \frac{T}3 dx$

...

$C_j[T]$= $\int_0^1 \frac{T}j dx$

Let's just say $j$ goes from 1 to 3.

Then I would expect you could easily compute these three integrals in a Do-loop.

For example

ClearAll["Global*"]
Do[Subscript[C, j][T_] :=  NIntegrate[(T/j), {x, 0, 1}], {j, 3}]


And let's say you want to plot $C_1[T]$...

Plot[Subscript[C, 1][T], {T, 0, 1}]


When you evaluate the cell, you get the following error:

NIntegrate::inumr: The integrand 0.0000204286/j has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>

This indicates that j is not being "seen" as it's numerical value, just the variable j, and therefore the integrand cannot be numerically integrated.

Does anyone know of a way to pass in the numerical value of the index j into NIntegrate when you're using it in a loop?

You are correct about having a scoping problem with your indexing variable, but you have another problem as well -- T in your Plot expression is not a function of x. Here is one way you might fix your code.

Clear[Subscript]
Do[With[{j = j}, Subscript[C, j][T_] := NIntegrate[(T/j), {x, 0, 1}]], {j, 3}]
Plot[Table[Subscript[C, j][1 + x^2], {j, 3}], {x, 0, 1}]


• Thanks - that worked; x was intended as a dummy variable for integration. It seems that the essential, missing component here was using With{j=j} Aug 2 '17 at 2:44
• @E.Scott. Passing an actual argument that is an expressed in terms of x to replace your formal argument Tis just as important using With. You have imbedded the symbol x into your definition of the various Subscript[C, j] forms and it must appear as the independent variable of the integrand. Aug 2 '17 at 7:25

Try this:

Table[Integrate[(T/j), {x, 0, 1}], {j, 3}]
`

You are using NIntegrate (numerical integration) but haven't defined T. Either use Integrate (as above) or give T a value.