How can I convert my MATLAB code into WL code?

I am working in MATLAB and want to convert the following snippet into WL code to run on Mathematica.

     u(j,j) = number1(j); //Some function of j that calculates the number
u(j,j+1) = number2(j);
u(j,j-1) = numer2(j);


The matrix u was not previously initialized. Basically I want to create a matrix which I can continuously append numbers to.

I know how to do something similar with vectors, namely,

u = {initialValue};


Hpw can I extend this to matrices for arbitrary $$j$$?

• Do you want a matrix with 3 bands? For size 5 try: SparseArray[{Band[{1, 1}] -> number1, Band[{2, 1}] -> number2, Band[{1, 2}] -> number2 }, {5, 5}] // MatrixForm – asterix314 Dec 10 '19 at 3:01
• @asterix314 Yes, but I should have added that number1, number2, and number3 change with j. which means that on {1,1} my number is 3, then j increments by one and now on {2,2} my number is 22.. etc. – DisPxy Dec 10 '19 at 3:14
• Don't ever "extend" matrices, not even in Matlab. Super inefficient. – Henrik Schumacher Dec 10 '19 at 7:12

SparseArray is especially versatile with how you specify the elements. E.g.
SparseArray[{{i_, i_} -> f[i], {i_, j_} /; Abs[i - j] == 1 -> g[i]}, {5, 5}] // MatrixForm

will produce the following matrix: $$\left( \begin{array}{ccccc} f(1) & g(1) & 0 & 0 & 0 \\ g(2) & f(2) & g(2) & 0 & 0 \\ 0 & g(3) & f(3) & g(3) & 0 \\ 0 & 0 & g(4) & f(4) & g(4) \\ 0 & 0 & 0 & g(5) & f(5) \\ \end{array} \right)$$