I want to plot a function with points and lines. I have to use ListPlot to make the plot.

Now, I have no problem getting the $y$ values, but the $x$ values are wrong. So I want to generate them with a For-loop in my plotting code. But what I've done does not work.

Can someone tell me how to improve it?

xk[k_, n_] := (-1 + k*1/(n/2))
xk[4, 7]
f[x_] := 1/(1 + 25 x^2)
fk[n_] := Table[f[xk[i, n]], {i, 0, n}]
ListPlot[for[i = 0, i <= 10, i++, {xk[i, 10], Part[fk[10], i]}]]
Plot[fk[xk[x, n], {x, 0, 10}]
  • 1
    $\begingroup$ Since you apparently know how to use Table, try using that instead of For. $\endgroup$
    – MarcoB
    Nov 30 '19 at 21:58

Another approach. One that I think is not only more concise, but more efficient and more elegant than using For.

f[x_] := 1/(1 + 25 x^2)

The built-in function Subdivide can be used to do the subdivision you perform with xk and Table, so those functions can be dispensed with. So all that is needed to generated the points you want to plot is:

fpts[n_] := With[{pts = Subdivide[-1, 1, n]}, Transpose[{pts, f /@ pts}]]

The plot is just

ListLinePlot[fpts[41], Mesh -> All, MeshStyle -> Red]


  • 1
    $\begingroup$ Just for the record: f[x] is the (in)famous Runge function: an infinitely differentiable function for which equidistant interpolating points on the x-axis give increasingly poorer polynomial approximations (especially toward the endpoints). (But the OP and you proabably already know that.) $\endgroup$
    – murray
    Dec 1 '19 at 20:35
  • $\begingroup$ @murray, Well, I didn't know it. Not a mathematician. Thanks for the additional info about the problem domain. $\endgroup$
    – m_goldberg
    Dec 2 '19 at 2:54

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.