ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 28 Aug 2019 14:00:23 +0200Given a matrix $M$ how to form the following matrix $N$ from $M$.https://ask.sagemath.org/question/47642/given-a-matrix-m-how-to-form-the-following-matrix-n-from-m/> Given a matrix $M$ how to form the following matrix $N$ from $M$.
Suppose $M=$\begin{bmatrix} 0 &3 \\ 2 &0 \end{bmatrix}
Here $M$ is a $2\times 2$ matrix with 1st row $[0,3]$ and 2nd row $[2,0]$.
We need to form $N$ such that
$N=$ \begin{bmatrix} 3& 3\\ 2&2\end{bmatrix}
Here $N$ is a $2\times 2$ matrix with 1st row $[3,3]$ and 2nd row $[2,2]$.
Thus $N$ is formed from $M$ by just adding all the off the diagonal elements of $M$ in a given row to the diagonal element
So the diagonal element of $N$ is the sum of all the remaining entries in a given row of $M$ whereas the rest of the elements of $N$ are the same as $M$.
So the elements of $N$ are obtained from $M$ in the following way :
$a_{11}=0+3=3, a_{12}=3,a_{21}=2,a_{22}=2+0=2$
How to code it?
Please help.Wed, 28 Aug 2019 13:40:55 +0200https://ask.sagemath.org/question/47642/given-a-matrix-m-how-to-form-the-following-matrix-n-from-m/Answer by tmonteil for <blockquote>
<p>Given a matrix $M$ how to form the following matrix $N$ from $M$.</p>
</blockquote>
<p>Suppose $M=$\begin{bmatrix} 0 &3 \ 2 &0 \end{bmatrix}</p>
<p>Here $M$ is a $2\times 2$ matrix with 1st row $[0,3]$ and 2nd row $[2,0]$.</p>
<p>We need to form $N$ such that </p>
<p>$N=$ \begin{bmatrix} 3& 3\ 2&2\end{bmatrix}</p>
<p>Here $N$ is a $2\times 2$ matrix with 1st row $[3,3]$ and 2nd row $[2,2]$.</p>
<p>Thus $N$ is formed from $M$ by just adding all the off the diagonal elements of $M$ in a given row to the diagonal element</p>
<p>So the diagonal element of $N$ is the sum of all the remaining entries in a given row of $M$ whereas the rest of the elements of $N$ are the same as $M$.</p>
<p>So the elements of $N$ are obtained from $M$ in the following way :</p>
<p>$a_{11}=0+3=3, a_{12}=3,a_{21}=2,a_{22}=2+0=2$ </p>
<p>How to code it?</p>
<p>Please help.</p>
https://ask.sagemath.org/question/47642/given-a-matrix-m-how-to-form-the-following-matrix-n-from-m/?answer=47644#post-id-47644Given a matrix `M`, you can get its `i`th row with `M.row(i)`, and the sum of its values with `sum(M.row(i))`. Now you just have to make a loop and modify diagonal elements step by step:
def myfunc(M):
assert M.is_square()
d,e = M.dimensions()
N = copy(M)
for i in range(d):
N[i,i] = sum(N.row(i))
return N
We have:
sage: M = matrix(2,2,[0,3,2,0])
sage: M
[0 3]
[2 0]
sage: myfunc(M)
[3 3]
[2 2]Wed, 28 Aug 2019 14:00:23 +0200https://ask.sagemath.org/question/47642/given-a-matrix-m-how-to-form-the-following-matrix-n-from-m/?answer=47644#post-id-47644