添加导致`MethodError:nomethodmatching+(::Array{Int64,0},::Int64)`

我正在使用 Julia,我尝试测试一个函数,该函数创建一个图像并根据给定的字符串分配 Red 值。仅仅听到这句话,我相信你可以想到我可以做的一百万件事情来接收错误消息,但是这个错误:

在第 13 行生成。

这是第 13 行:

r = (i + 64*rand(0:3) - 1)/255

那只是数学!r 是我在那里分配的一个新变量。i 是数组中每个字符的索引。这似乎在控制台中有效,所以之前的代码中可能发生了一些奇怪的事情,只是没有被捕获。这是整个功能:

function generate(string, width)
  img = rand(RGB,width,floor(Int,length(string)/width) + 1)
  for n in 1:length(string)
    i = indexin(string[n], alphabet)
    r = (i + 64*rand(0:3) - 1)/255
    g = img[n].g
    b = img[n].b
    img[n] = RBG(r,g,b)
  end
  return img
end

有谁知道这个错误信息是什么意思,或者我做错了什么?

回答

i在这里不是一个整数,它是一个数组。indexin用于查找数组中每个元素在另一个元素中的位置;只找到一个你可能想要的元素findfirst

julia> findfirst(isequal('c'), collect("abcde"))
3

julia> indexin(collect("cab"), collect("abcde"))
3-element Vector{Union{Nothing, Int64}}:
 3
 1
 2

julia> indexin('c', collect("abcde"))
0-dimensional Array{Union{Nothing, Int64}, 0}:
3

另请注意,nothing如果他们找不到这封信,这两者都会给出,您可能想决定如何处理。(可能与if else,您也可以使用功能something。)

julia> indexin('z', collect("abcde"))
0-dimensional Array{Union{Nothing, Int64}, 0}:
nothing

julia> findfirst(isequal('z'), collect("abcde")) === nothing
true

最后,请注意索引这样的字符串不是很健壮,您可能需要迭代它:

julia> "cañon"[4]
ERROR: StringIndexError: invalid index [4], valid nearby indices [3]=>'ñ', [5]=>'o'

julia> for (n, char) in enumerate("cañon")
       @show n, char
       end
(n, char) = (1, 'c')
(n, char) = (2, 'a')
(n, char) = (3, 'ñ')
(n, char) = (4, 'o')
(n, char) = (5, 'n')

  • 此外,OP 可能希望对“findfirst”的输出进行“isnothing”检查,以防它返回,好吧,“nothing”。

以上是添加导致`MethodError:nomethodmatching+(::Array{Int64,0},::Int64)`的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>