ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 11 Feb 2018 14:33:28 -0600iteration of a matrixhttp://ask.sagemath.org/question/41064/iteration-of-a-matrix/ Hello community,
I have the following question. I have a matrix defined as K. And its diagonal defined, for instance, as `z = [1, 2, 3, 4, 5]`. I need to change each entry of a diagonal one by one, and then check a condition using 'if' statement. For example, change z to `[2, 2, 3, 4, 5] ` and then `[1, 3, 3, 4, 5]` and then `[1, 2, 4, 4, 5]` (increasing each element by 1)
Now I have a code :
for i in range(16):
K1 = K
K1[i,i] = K[i,i] + 1
V1 = p1 * K1 * p1t
V2 = p2 * K1 * p2t
if V2 < V1:
print i
So the first three rows are more interesting for the problem. The problem is, this code changes each entry, not returning the previous one to the initial position. So it changes the diagonal as following: `[1, 2, 3, 4, 5]` to `[2, 2, 3, 4, 5]` to `[2, 3, 3, 4, 5]` to `[2, 3, 4, 4, 5]` etc. How can I modify this code to correct the problem? Thank you.Sun, 11 Feb 2018 11:56:11 -0600http://ask.sagemath.org/question/41064/iteration-of-a-matrix/Answer by dan_fulea for <p>Hello community, </p>
<p>I have the following question. I have a matrix defined as K. And its diagonal defined, for instance, as <code>z = [1, 2, 3, 4, 5]</code>. I need to change each entry of a diagonal one by one, and then check a condition using 'if' statement. For example, change z to <code>[2, 2, 3, 4, 5]</code> and then <code>[1, 3, 3, 4, 5]</code> and then <code>[1, 2, 4, 4, 5]</code> (increasing each element by 1)</p>
<p>Now I have a code : </p>
<pre><code>for i in range(16):
K1 = K
K1[i,i] = K[i,i] + 1
V1 = p1 * K1 * p1t
V2 = p2 * K1 * p2t
if V2 < V1:
print i
</code></pre>
<p>So the first three rows are more interesting for the problem. The problem is, this code changes each entry, not returning the previous one to the initial position. So it changes the diagonal as following: <code>[1, 2, 3, 4, 5]</code> to <code>[2, 2, 3, 4, 5]</code> to <code>[2, 3, 3, 4, 5]</code> to <code>[2, 3, 4, 4, 5]</code> etc. How can I modify this code to correct the problem? Thank you.</p>
http://ask.sagemath.org/question/41064/iteration-of-a-matrix/?answer=41069#post-id-41069Use a `copy` of `K` instead, e.g.
sage: K = diagonal_matrix( QQ, [1,2,3,4,5] )
sage: K1 = copy(K)
sage: K1[0,0] += 1
sage: K1
[2 0 0 0 0]
[0 2 0 0 0]
[0 0 3 0 0]
[0 0 0 4 0]
[0 0 0 0 5]
sage: K
[1 0 0 0 0]
[0 2 0 0 0]
[0 0 3 0 0]
[0 0 0 4 0]
[0 0 0 0 5]
Sun, 11 Feb 2018 14:33:28 -0600http://ask.sagemath.org/question/41064/iteration-of-a-matrix/?answer=41069#post-id-41069