0
$\begingroup$

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}; 
While[..., AppendTo[u, someNumber[i]], ...]

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

$\endgroup$
3
  • $\begingroup$ 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 $\endgroup$
    – asterix314
    Dec 10, 2019 at 3:01
  • $\begingroup$ @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. $\endgroup$
    – DisPxy
    Dec 10, 2019 at 3:14
  • 1
    $\begingroup$ Don't ever "extend" matrices, not even in Matlab. Super inefficient. $\endgroup$ Dec 10, 2019 at 7:12

1 Answer 1

10
$\begingroup$

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) $$

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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