# Diagonal matrix command in Mathematica

How to find the corresponding Mathematica commands for diagonal matrix operation in Matlab, e.g.

 AA=rand(3,3);


Step 1.) finding the diagonal elements, and export them as a list "tmp"

tmp = spdiags(AA,0);


Step 2.) modifying one list element

tmp(2)=1;


Step 3.) return the changed diagonal elements in matrix backmat

backmat=spdiags(tmp,0,AA); % reinsert diagonal;


How can we define the Step 1 & Step 3 in Mathematica 12.2?

• Can you, please, describe what each step is doing here? It is not clear what is being done in these steps. Commented May 23, 2021 at 1:44
• @CATrevillian just check now! simple test! Commented May 23, 2021 at 1:45
• Use the concrete example instead of MatLab code will make it easy to understand. Commented May 23, 2021 at 1:53
• Please show us the desired input and output rather than MATLAB code. Commented May 23, 2021 at 1:58

AA=rand(3,3)
tmp = spdiags(AA,0)
tmp(2)=1
backmat=spdiags(tmp,0,AA);
full(backmat)


gives

AA =
0.6948    0.0344    0.7655
0.3171    0.4387    0.7952
0.9502    0.3816    0.1869

tmp =
0.6948
0.4387
0.1869

tmp =
0.6948
1.0000
0.1869

ans =
0.6948    0.0344    0.7655
0.3171    1.0000    0.7952
0.9502    0.3816    0.1869


In Mathematica

(AA = {{0.6948, 0.0344, 0.7655}, {0.3171, 0.4387, 0.7952}, {0.9502,
0.3816, 0.1869}}) // MatrixForm
tmp = Diagonal[AA, 0];
tmp[[2]] = 1;
backmat =
SparseArray[Band[{1, 1}] -> tmp] +
SparseArray@UpperTriangularize[AA, 1] +
SparseArray@LowerTriangularize[AA, -1]
MatrixForm[backmat]


Gives

I do not think Mathematica has command to insert diagonal into sparse matrix directly like Matlab's spdiags but it is possible to do it as above indirectly.

• NICE work! thanks! can we use other commands in MMA 12.2 ? Commented May 23, 2021 at 2:25
• what is the meaning of Band[{1, 1}] in this case? Commented May 23, 2021 at 2:27
• @a Then why not AA[[2,2]]=1? Commented May 23, 2021 at 2:29
• @xzczd here, we use a very simple test case to understand this issue, the real case is that we need to modify a very large sparse matrix using "% reinsert diagonal;"... Commented May 23, 2021 at 2:34
• @a Sparse matrix isn't a problem, AA in AA[[2,2]]=1 can be a SparseArray. Commented May 23, 2021 at 2:48