Julia BoundsError 信息较少 - 不知道为什么

问题描述

我有以下代码

# package for ploting functions
using Plots
# use GR
gr()


# nb points to plot
nbPts = 22

# define polar coordinates of a 30 degree (pi/6) rotation
sine = sin(pi/6)
cosine = cos(pi/6)

# scale factor
scale_factor = 0.9




#---------------------------------------
# 1. PLOT POINTS USING ROTATION MATRIX
#---------------------------------------


# define Rotation matrix ( angle = pi/6,center = (0,0) )
R = zeros(Float64,2,2)
R[1,1] = R[2,2]= cosine
R[1,2] = -sine
R[2,1] = sine

# Scale matrix

        ### ...   <-- EXERCISE 4(c): define a uniform scaling matrix (use scale_factor)


# arrays of points coords
X_mat = zeros(nbPts)
Y_mat= zeros(nbPts)

# first Point (1,0)
X_mat[1] = 1.0
Y_mat[1] = 0.0

for i in 2:nbPts

    prevPoint = [X_mat[i-1],Y_mat[i-1]]
    #apply rotation to prevIoUs point to obtain new point
    newPoint = R * prevPoint

        ### ...   <-- EXERCISE 4(c): apply scaling matrix

    X_mat[i] = newPoint[1]
    Y_mat[i] = newPoint[2]

end

# plot points in blue
plt1 = scatter(X_mat,Y_mat,color=:blue,xlim = (-1.1,1.1),ylim = (-1.1,label=false,title="Rotation using matrices" );





#---------------------------------------
# 2. PLOT POINTS USING COMPLEX NUMBERS
#---------------------------------------

function ComplexProduct(z,w)
    (((z[1]*w[1])+(z[2]*w[2])),((z[1]*w[2])+(z[2]*w[1])))

    ### ...   <-- EXERCISE 4(b): implement complex product z * w

end


# first point: z = 1 + 0 * i
Z = ( 1.0,0.0 )
# second point: w = cosine( pi/6) + sine( pi/6) * i
W = ( cosine,sine )

    ### ...   <-- EXERCISE 4(c): apply scale_factor to W


# arrays of points coords
X_comp = zeros(nbPts)
Y_comp = zeros(nbPts)

# first Point (1,0)
X_comp[1] = Z[1]
Y_comp[1] = Z[2]

for i in 2:nbPts

    prevPoint = (X_comp[i-1],Y_comp[i-1])

    newPoint = ComplexProduct(prevPoint[1],prevPoint[2])   ###  <-- EXERCISE 4(b): compute newPoint by applying rotation to prevPoint (use complex product)

    X_comp[i] = newPoint[1]
    Y_comp[i] = newPoint[2]

end

# plot points in red
plt2 = scatter(X_comp,Y_comp,color=:red,title="Rotation using complex numbers" );





# arrange and display
display( plot( plt1,plt2,layout = (1,2),size=(600*2,600) ))

错误

Error Code

我想要的东西: 我必须实现复数的乘积,这应该用于计算复数的旋转。

应该是这样的:

rotaion

我必须更改什么才能修复 BoundsError? 不知道我到底做错了什么,因为我从这个错误日志中得到的信息很差。

问候并感谢您的帮助。

解决方法

prevPoint[1] 是一个标量,而您的函数 ComplexProduct 需要具有 2 元素的东西。也许您想传递 prevPoint 而不是 prevPoint[1]

顺便说一句,您使用了不正确的命名模式。不鼓励 Julia 使用 CamelNaming。 您的变量应命名为 prev_point,函数应命名为 complex_product

,

通过更改以下代码修复了错误:

newPoint = ComplexProduct(prevPoint,W)

在第 92 行