Ask Your Question
0

iteration of a matrix

asked 2018-02-11 11:56:11 -0600

Xenia gravatar image

updated 2018-02-11 11:58:53 -0600

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.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2018-02-11 14:33:28 -0600

dan_fulea gravatar image

Use 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]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-02-11 11:56:11 -0600

Seen: 23 times

Last updated: Feb 11