By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,748 Members | 1,251 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,748 IT Pros & Developers. It's quick & easy.

Scope Problems (I think?)

P: 6
Hey all,
I'm making a program to solve systems of equations using Cramer's rule. Here's how part of it works:
Take a matrix (let's say it's 3*3). I represent this matrix by a 2D array, containing each row in an array. [[the,top,row],[m,i,d],[b,o,t]].
Then, I have a column of numbers, (1 column wide, and we'll say 3 high, again).
Cramer's rule works by replacing the first column in the 3*3 matrix with the new column, then performing a calculation. Then, take the ORIGINAL matrix and replace the SECOND column with the new column, and perform the calculation. then, do the same thing with the THIRD column...
In other words:
Expand|Select|Wrap|Line Numbers
  1. def repCol(m, j, col):
  2.     #For consistency, we will define j on the scale of (0,x), not (1,x)
  3.     for row in range(0,len(col)):
  4.         m[row][j] = col[row]
  5.     return m
  6.  
  7. def cramer(exp, sol):
  8.     solutions = []
  9.     D = float(det(exp))
  10.     print D
  11.     for var in range(0,len(exp)):
  12.         solutions.append(det(repCol(exp,var,sol))/D)
  13.         print exp
  14.     return solutions
  15.  
I'm running the cramer function, with exp being the 3*3, and sol being the 3*1 array.

The first replacement and calculation go fine. The problem is on the second one. It ends up having replaced the first and the second columns, instead of just the second. I think the problem is that the repCol function doesn't just return the modified matrix, but it modifies the ORIGINAL matrix.
How do I fix this?
Aug 6 '08 #1
Share this Question
Share on Google+
1 Reply

boxfish
Expert 100+
P: 469
Hi,
Yes, it probably does modify the original matrix. You need to make a new matrix and use a loop to explicitly copy all the values in, or import copy and use its handy deepcopy() function.
Expand|Select|Wrap|Line Numbers
  1. import copy
  2. my_nice_new_copied_matrix = copy.deepcopy(m)
Hope this helps.
Aug 8 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.