【问题标题】:Addition leads to `MethodError: no method matching +(::Array{Int64, 0}, ::Int64)`加法导致 `MethodError: no method matching +(::Array{Int64, 0}, ::Int64)`
【发布时间】:2021-09-21 07:17:29
【问题描述】:

我正在使用 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

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

【问题讨论】:

  • 不要先进行浮点除法,然后用floor(Int,length(string)/width) 进行舍入,而应直接使用div 函数进行整数除法:div(length(mystring), width)。
  • 请不要发布代码/错误/数据的图像。而是将代码/错误/数据作为文本发布在代码块中。见How do I ask a good question?

标签: math julia pixel-manipulation


【解决方案1】:

您的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 可能需要isnothing 检查findfirst 的输出,以防它返回,好吧,nothing。
  • 谢谢,我编辑添加了一些关于此的内容。
猜你喜欢
  • 2017-04-11
  • 2020-07-05
  • 2016-06-04
  • 1970-01-01
  • 2022-01-24
  • 2023-03-27
  • 2016-12-30
  • 1970-01-01
  • 2019-07-27
相关资源
最近更新 更多