【问题标题】:How to vectorize more than one vector in Julia?如何在 Julia 中向量化多个向量?
【发布时间】:2021-09-13 10:44:39
【问题描述】:

我想在 Julia 中编写向量化样式代码,希望定义一个函数,该函数将多个向量作为参数,如下所示。

[代码]

using PyPlot;
m=[453 21 90;34 1 44;13 553 66]
a = [1,2,3]
b=[1,2,3]
f(x,y) = m[x,y]
f.(a,b)

#= expected result
3×3 Matrix{Int64}:
 453   21  90
  34    1  44
  13  553  66
#

[实际结果]

3-element Vector{Int64}:
 453
   1
  66

点表示法只选择每行的第一个元素,忽略其他元素,并生成一个只有 3 个元素的向量,而不是 3 x 3 矩阵。

如何写才能得到预期的结果?

任何信息将不胜感激。

【问题讨论】:

    标签: python arrays function numpy julia


    【解决方案1】:

    两个向量之一需要是行向量,这样 Julia 才能理解你想要做什么,这个简单的例子应该可以帮助你理解 Julia 广播:

    julia> [1,2,3] .+ [10,20,30] # both have the same dimensions
    3-element Vector{Int64}:
     11
     22
     33
    
    julia> [1,2,3]' .+ [10,20,30] 
    # first has dimensions (1,3) and second (3,1) => result is dimension (3,3)
    3×3 Matrix{Int64}:
     11  12  13
     21  22  23
     31  32  33
    

    【讨论】:

      【解决方案2】:

      你在寻找

      julia> f.(a, b')
      3×3 Matrix{Int64}:
       453   21  90
        34    1  44
        13  553  66
      

      注意broadcast 文档中的相关部分(在 REPL 会话中键入 ?broadcast 以访问它):

      通过虚拟重复值来扩展单个维度和缺失维度以匹配其他参数的范围。

      a 被视为 3x1 矩阵(但类型为 Vector{T}),而 b' 被用作 1x3 矩阵(类型为 Adjoint(T, Vector{T}))。这些被广播到生成的 3x3 矩阵。

      当直接使用ab 时,不需要扩展维度,您最终会得到一个 3x1 矩阵。

      【讨论】:

      • 谢谢。我得到了它。仅仅通过阅读官方文档来了解 Julia 对我来说是一项艰巨的工作。
      猜你喜欢
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2014-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多