2
$\begingroup$

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?

$\endgroup$
4
  • $\begingroup$ Can you, please, describe what each step is doing here? It is not clear what is being done in these steps. $\endgroup$ May 23 at 1:44
  • $\begingroup$ @CATrevillian just check now! simple test! $\endgroup$
    – ABCDEMMM
    May 23 at 1:45
  • 1
    $\begingroup$ Use the concrete example instead of MatLab code will make it easy to understand. $\endgroup$
    – cvgmt
    May 23 at 1:53
  • $\begingroup$ Please show us the desired input and output rather than MATLAB code. $\endgroup$
    – xzczd
    May 23 at 1:58
7
$\begingroup$
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

Mathematica graphics

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.

$\endgroup$
7
  • $\begingroup$ NICE work! thanks! can we use other commands in MMA 12.2 ? $\endgroup$
    – ABCDEMMM
    May 23 at 2:25
  • $\begingroup$ what is the meaning of Band[{1, 1}] in this case? $\endgroup$
    – ABCDEMMM
    May 23 at 2:27
  • $\begingroup$ @a Then why not AA[[2,2]]=1? $\endgroup$
    – xzczd
    May 23 at 2:29
  • $\begingroup$ @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;"... $\endgroup$
    – ABCDEMMM
    May 23 at 2:34
  • 1
    $\begingroup$ @a Sparse matrix isn't a problem, AA in AA[[2,2]]=1 can be a SparseArray. $\endgroup$
    – xzczd
    May 23 at 2:48

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.