尝试在 while 循环中调用二维数组中的元素(python/numpy)
我正在尝试创建一个程序,将任何给定的矩阵减少为减少的行梯形形式。
我想要的是将行中的每个条目除以前导数字。例如,假设我有:
[ [3, 4, 5], [ 1, 2, 3] ] # a 2-d array. which gives:
[ 3, 4, 5]
[ 1, 2, 3]
我正在尝试将其转换为 [ 1 , 4/3, 5/3] 。但是,如果您遵循我的代码:
def npgauss(a):
n = 0
for i in a[0]:
x = a[0][0]
a[0][n] = a[0][n]/x
print a[0][n]
n = n + 1
您会发现我的问题是第一个条目被自身除以 1,然后当它转到第二个条目时,它将除以新的数字 1 而不是原始数字 1 3号(这就是我想要的)。
我想不出解决办法!我该如何使它除以原始数字?
I am trying to create a program that reduces any given matrix to reduced row echelon form.
What I'm trying to is to divide each entry in the row by the leading number. For example, say I have:
[ [3, 4, 5], [ 1, 2, 3] ] # a 2-d array. which gives:
[ 3, 4, 5]
[ 1, 2, 3]
I'm trying to turn that into [ 1 , 4/3, 5/3]. However, if you follow my code:
def npgauss(a):
n = 0
for i in a[0]:
x = a[0][0]
a[0][n] = a[0][n]/x
print a[0][n]
n = n + 1
you'll see that my problem is that the 1st entry get divided by itself to give 1, and then when it goes to the second entry, it divides that by the new number 1 instead of the original number 3 (which is what I want).
I can't figure out a way around this! How do I make it so that it divides by the original number?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于问题提到了 numpy,这里有一个不使用循环的解决方案:
给出所需的结果
这里有一些微妙之处:
a [:,0:1]
而不是a[:,0]
来选择第一列a /= a[:,0:1]
因为就地运算符认为由于某种原因数组广播不同Since the question mentions numpy, here is a solution without using loops:
gives the required result
There are a few subtleties here:
a[:,0:1]
instead ofa[:,0]
to select the first columna /= a[:,0:1]
since the in-place operators treat array broadcasting differently for some reason如果您希望在整个循环中固定 x ,只需在进入循环之前设置其值即可:
If you want
x
fixed for the whole loop, just set its value before you go into the loop:您可以使用 列表推导式 来完成此操作
You can do this using list comprehensions