微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python中的矩阵点积返回“索引过多”错误

如何解决Python中的矩阵点积返回“索引过多”错误

import numpy as np

#initialize the vectors a and b

a = np.array(input('Enter the first vector: '))
b = np.array(input('Enter the second vector: '))

#Evaluate the dot product using numpy

a_dot_b = 0
for i in range(3):
    a_dot_b += a[i] * b[i]

if a_dot_b == 0:
    print("The vectors are orthogonal")
else:
    print("Dot product = ",a_dot_b)

我正在尝试编写一个程序,告诉用户两个向量是否正交。当我尝试运行它时,它说IndexError: too many indices for array 我不知道是我的循环出了问题,还是我输入向量的问题。

解决方法

由于 input() 返回一个字符串,ab 是一个字符数组。因此,您需要将输入字符串拆分为向量条目并将每个元素转换为浮点数。假设您输入的向量元素为 1,2,3,您可以这样做:

import numpy as np

#initialize the vectors a and b

a = np.array([float(i) for i in input('Enter the first vector: ').split(",")])
b = np.array([float(i) for i in input('Enter the second vector: ').split(",")])

#Evaluate the dot product using numpy

a_dot_b = 0
for i in range(3):
    a_dot_b += a[i] * b[i]

if a_dot_b == 0:
    print("The vectors are orthogonal")
else:
    print("Dot product = ",a_dot_b)

请注意,您不需要循环来计算点积。您可以使用 np.dot(a,b)

,

这里可以。你不能真正得到这样的数组:

function isTouchDevice() {
  return (('ontouchstart' in window) ||
     (navigator.maxTouchPoints > 0) ||
     (navigator.msMaxTouchPoints > 0));
}

a = np.array(input('Enter the first vector: ')) 返回单个值。你需要一些东西

input

a = [] n = int(input("Enter the number of elements: ")) # iterating till the range for i in range(n): a.append(float(input(f'Enter element #{i}:'))) a = np.array(a)

相同

还有你的循环

b

假设两个数组中正好有三个元素。您可能想将其替换为

for i in range(3):
...

并且在您要求用户输入时确保 for i in range(len(a)): ... a 的长度始终相同,或者专门检查并引发错误

,

在 NumPy 中,您应该使用 [] 确定数组的维数,这里您将一个零维数的字符串提供给 NumPy 并尝试迭代,因此您得到了错误。 你可以把你的代码改成这样:

# get the first vector from user
firstVector = [int(i) for i in input('Enter the first vector: ').split()]
# convert into numpy array
a = np.array(firstVector)
# get the second vector from user
secondVector = [int(i) for i in input('Enter the second vector: ').split()]
# convert into numpy array
b = np.array(secondVector)

其余代码相同。

代码第二部分的替代解决方案: 在 NumPy 中,您只能使用以下代码找到两个向量的点积:

1) sum(a * b)
2) np.dot(a,b)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。