1
$\begingroup$

The following code is syntactically correct (I receive no error message) but it does not print the matrix I am expecting. In fact, it does not print anything at all. I expect:

$\begin{bmatrix} d & 1 & 0 \\ 1 & -c & -1 \\ 0 & 1 & 1/b-1/c \end{bmatrix}$

pcomb[n_]:= (
  matt=ConstantArray[0, {n, n}];
  matt[[1, 1]] = d;
  matt[[1, 2]] = 1;
  For [q = 1, q < n - 2, q++, 
    If[EvenQ[q - 1],
      matt[[q + 1, q]] = 1;
      matt[[q + 1, q + 1]] = -c;
      matt[[q + 1, q + 2]] = 1;
    ,
      matt[[q + 1, q]] = 1;
      matt[[q + 1, q + 1]] = d;
      matt[[q + 1, q + 2]] = 1;]];
  matt[[n - 1, n - 2]] = 1;
  matt[[n - 1, n - 1]] = -c;
  matt[[n - 1, n]]= -1;
  matt[[n, n - 1]] = 1;
  matt[[n,n]] = 1/b-1/c;
  matt;)

pcomb[7]

I've checked out the following tutorial but did not find it useful to pinpoint my mistake. I also looked at Wolfram's reference for procedural programming.

http://www.wolfram.com/language/fast-introduction-for-programmers/en/pure-functions/

$\endgroup$
2
  • $\begingroup$ Try ending with matt) instead of matt;) $\endgroup$
    – Carl Woll
    Jul 31 '17 at 4:52
  • $\begingroup$ You might want to consider using SparseArray[]: With[{n = 7}, SparseArray[{{n - 1, n} -> -1, {n, n} -> 1/b - 1/c, Band[{2, 1}] -> 1, Band[{1, 2}] -> 1, Band[{1, 1}, {n - 1, n - 1}] -> {d, -c}}, {n, n}]]. Where did this tridiagonal matrix come from? $\endgroup$
    – J. M.'s torpor
    Jul 31 '17 at 5:23
4
$\begingroup$

The semi-colon at the end of the line matt; ensures that your function pcomb doesn't actually return anything. For a multiline function, you want to use Function (and/or Module or Block) instead of parentheses. Writing instead:

pcomb = Function[{n},
   Block[{matt = ConstantArray[0, {n, n}]},
    matt[[1, 1]] = d;
    matt[[1, 2]] = 1;
    For[q = 1, q < n - 2, q++, If[EvenQ[q - 1], matt[[q + 1, q]] = 1;
      matt[[q + 1, q + 1]] = -c;
      matt[[q + 1, q + 2]] = 1;,
      matt[[q + 1, q]] = 1;
      matt[[q + 1, q + 1]] = d;
      matt[[q + 1, q + 2]] = 1;]];
    matt[[n - 1, n - 2]] = 1;
    matt[[n - 1, n - 1]] = -c;
    matt[[n - 1, n]] = -1;
    matt[[n, n - 1]] = 1;
    matt[[n, n]] = 1/b - 1/c;
    matt
    ]
   ];

gets the desired output from pcomb[7].

$\endgroup$

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.