-5
$\begingroup$

Why does the following code not work?

t=1;h=0.1;n=t/h+1;m=3;
W=Table[0,{n},{m+1}];
for[k=2,k<m+1,k++,
  f=Table[0,{n-2},{n-2}];
  f[[1,1]]=2-1/(1+10*h)+10*h*h*W[[2,k]];f[[1,2]]=-1+5*h;
  for[i=2,i<n-2,i++,
    f[[i,i]]=2+10*h*h*W[[i+1,k]];
    f[[i,i-1]]=-1-5*h;
    f[[i,i+1]]=-1+5*h;];
    f[[n-2,n-2]]=5*h+1+10*h*h*W[[n-1,k]];
  f[[n-2,n-3]]=-1-5*h;
  F=Table[0,{n-2}];
  for[i=1,i<n-1,i++,
    F[[i]]=
      -W[[i+2,k]]+2*W[[i+1,k]]-W[[i,k]]+
      5*h*(W[[i+2,k]-W[[i,k]])+
      5*h*h*W[[i+1,k]]*W[[i+1,k]];];

A=Linear Solve[f,-F];
for[i=2,i<n,i++,
   W[[i,k+1]]=W[[i,k+1]]+A[[i]]];
   W[[1,k+1]]=(W[[2,k+1]]+50*h)/(10*h+1);
   W[[n,k+1]]=W[[n-1,k+1]]];
$\endgroup$
  • 7
    $\begingroup$ 1) please format your code, add line breaks, and indent it for readability. 2) For should be uppercase 3) you should avoid For loops. $\endgroup$ – MarcoB Dec 10 '19 at 2:43
  • 2
    $\begingroup$ There are syntax errors in your code. Use For not for; LinearSolve not Linear Solve; and there is a extra ] in last For-loop. $\endgroup$ – m_goldberg Dec 10 '19 at 5:03
  • $\begingroup$ F comes out as {0, 0, 0, 0, 0, 0, 0, 0, 0} because there is no code to populate W, $\endgroup$ – m_goldberg Dec 10 '19 at 5:20
  • $\begingroup$ In the last inner For-loop, (W[[i + 2, k] - W[[i, k]]) should be (W[[i + 2, k]] - W[[i, k]]) $\endgroup$ – m_goldberg Dec 10 '19 at 5:25
1
$\begingroup$

This may be a partial answer. As I understand it your elaborate calculation of f can be replaced with:

t = 1;
h = 1/10;
n = t/h + 1;
f = 
  SparseArray[{Band[{1, 2}] -> -1/2, Band[{1, 1}] -> 2, Band[{2, 1}] -> -3/2}, n - 2]
f[[1, 1]] = f[[-1, -1]] = 3/2;
f // MatrixForm

matrix

$\endgroup$

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