【问题标题】:How to apply function elementwise in Julia?如何在 Julia 中逐元素应用函数?
【发布时间】:2016-07-20 19:52:24
【问题描述】:

有一个函数h(x) = ([1, x]' * [2, 3])[1]

假设我想绘制它并得到XY。一种可能的方法是关注

X = [1 2 3]
Y = [h(xi) for xi in X]

但是,在 Julia 中使用元素运算符似乎也可以做到这一点?

不幸的是,在函数前面加上点 .h(X) 不起作用。

【问题讨论】:

  • map(h, X) 你在这里找什么?
  • 这是一个普遍的问题,或者您是否想要为您的示例提供元素解决方案?我相信您的示例可以向量化。但是对于通用方法map 是@niczky12 建议的解决方案。
  • 是的,我已经询问了一般方法。
  • 获取 Julia 1.X 的最新答案会很有用。

标签: julia


【解决方案1】:

更新f.(x) 语法已合并并在 julia v0.5 中可用,请参阅 the documentWIP

@vectorize_1arg 在 julia 的 Base 中可以使您的函数可以接受数组。用这个宏包裹你的h 可能会解决问题。

这是来自julia document的示例

julia> square(x) = x^2
square (generic function with 1 method)

julia> @vectorize_1arg Number square
square (generic function with 4 methods)

julia> methods(square)
# 4 methods for generic function "square":
square{T<:Number}(::AbstractArray{T<:Number,1}) at operators.jl:380
square{T<:Number}(::AbstractArray{T<:Number,2}) at operators.jl:381
square{T<:Number}(::AbstractArray{T<:Number,N}) at operators.jl:383
square(x) at none:1

julia> square([1 2 4; 5 6 7])
2x3 Array{Int64,2}:
  1   4  16
 25  36  49

如果您正在寻找更“优雅”的方法,here is a discussion about 为这个问题添加新语法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多