1

I have this code:

Subscript[t, 0] = 0  ;
x[Subscript[t, 0]] = 1  ;
h = 0.2;
For[l = 0, l <= 2, Subscript[t, l + 1] = Subscript[t, l] + h; 
  Print["t[", l, "]= ", N[Subscript[t, l], 2]]; l++];
For[r = 0, r <= 2, 
  x[Subscript[t, r + 1]] = 
   x[Subscript[t, 
     r]] + (Subscript[t, r + 1] - Subscript[t, 
       r])*(x[Subscript[t, r]] + Subscript[t, r]^2); 
  Print["x[t", r, "]= ", N[x[Subscript[t, r]], 2]]; r++];

and output is:

I want to draw plot a list of points with specified ti and x[ti] coordinates.

ListPlot[Table[{Subscript[t, i], x[Subscript[t, i]]}, {t, 0, 2, 1}], 
 Filling -> Axis]
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Bahram Agheli
  • 504
  • 2
  • 12

2 Answers2

6

Always avoid using subscripts, they just confuse things. Instead of defining Subscript[t,0]=0, define t[0]=0. Finally, Do loops are easier to read and write than For loops, which generally come from other programming languages.

Does this do what you were going for?

t[0] = 0;
x[0] = 1;
h = 0.2;
Do[
 t[n + 1] = t[n] + h;
 x[n + 1] = x[n] + (t[n + 1] - t[n]) (x[n] + t[n]^2);
 , {n, 0, 3}]

To see what you've assigned to t and x, use this:

?x
?t

enter image description here

ListPlot[Table[{t[n], x[n]}, {n, 0, 4}]]

enter image description here

Jason B.
  • 68,381
  • 3
  • 139
  • 286
4

I would suggest separating the substance of your computation from the labels/formats. I also suggest searching this site on reasons for avoiding for loops. For example,

fun[n_, h_] := 
 NestList[{#[[1]] + h, #[[2]] + h (#[[2]] + #[[1]]^2)} &, {0, 1}, n]

codes your function (barring any error on my part). Then,

TableForm[fun[5,0.2], 
 TableHeadings -> {Range[0, 5], {"\!\(\*SubscriptBox[\(t\), \(n\)]\)",
     "\!\(\*SubscriptBox[\(x\), \(n\)]\)"}}]
ListPlot[fun[5,0.2]]

yields:

enter image description here

ubpdqn
  • 60,617
  • 3
  • 59
  • 148