程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Python中的矩阵点积返回“索引过多”错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到Python中的矩阵点积返回“索引过多”错误的问题如何解决?下面主要结合日常开发的经验,给出你关于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)

大佬总结

以上是大佬教程为你收集整理的Python中的矩阵点积返回“索引过多”错误全部内容,希望文章能够帮你解决Python中的矩阵点积返回“索引过多”错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: