# Building a matrix procedurally

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


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/

• Try ending with matt) instead of matt;) Jul 31 '17 at 4:52
• 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? Jul 31 '17 at 5:23

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.