Ask Your Question
0

Need only the final result of for loop

asked 2017-02-20 07:19:51 +0100

Deepak Sarma gravatar image

updated 2017-02-20 07:42:39 +0100

tmonteil gravatar image

Suppose I want to increase each off diagonal element of a matrix by 1. Myy program gives me a sequence of matrices each time changing only one entry. I just need the final matrix of the sequence. Please check the following program. What modification is required so that the program changes all the entries at a time?

A=random_matrix(QQ,5,5)
B=copy(A)
for i in range(A.nrows()):
    for j in range(A.nrows()):
        if i!=j:
            B[i,j]=A[i,j]+1
            print A,B
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2017-02-26 16:49:17 +0100

dan_fulea gravatar image

The question was strictly asking how to perform all add-one operations at once. (That print command was of course misplaced in the inner most loop.)

An answer constructs the B-copy already with the right entries. For me works best:

A = random_matrix( QQ, 5, 5 )
B = matrix( QQ, 5, 5, [ A[n,k]+1 for n in range(5) for k in range(5) ] )
print A
print B
edit flag offensive delete link more

Comments

Thank you.

Deepak Sarma gravatar imageDeepak Sarma ( 2017-03-05 16:56:38 +0100 )edit
1

answered 2017-02-20 07:44:02 +0100

tmonteil gravatar image

Is it homework ? If yes, you should learn about indentation in Python (hence Sage).

edit flag offensive delete link more

Comments

Thank you for your response. I have recently started learning sage(python). But what I know is, if indentations were not appropriate, there would be some error while running my code? Is it? My program ran succesfully, the only problem I have is that it is giving me a lot of unnecessary outputs.

Deepak Sarma gravatar imageDeepak Sarma ( 2017-02-20 11:34:58 +0100 )edit

You got a broad hint: it's a matter of indentation. Change the level of indentation of the print statement and see what happens.

ndomes gravatar imagendomes ( 2017-02-20 21:58:52 +0100 )edit

Got it. Thank you

Deepak Sarma gravatar imageDeepak Sarma ( 2017-03-08 06:09:12 +0100 )edit

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2017-02-20 07:19:51 +0100

Seen: 236 times

Last updated: Feb 26 '17