本文介绍了嵌套数组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一组向量:

""" simple line equation """
function getline(a::Array{Float64,1},b::Array{Float64,1})
    line = Vector[]
    for i=0:0.1:1
        vector = (1-i)a+(i*b)
        push!(line, vector)
    end
    return line
end

该函数返回一个包含 x-y 位置的向量数组

This function returns an array of vectors containing x-y positions

Vector[11]
 > Float64[2]
 > Float64[2]
 > Float64[2]
 > Float64[2]
  .
  .
  .

现在我想分离这些向量的所有 x 和 y 坐标,用 plotyjs 绘制它们.

Now I want to seprate all x and y coordinates of these vectors to plot them with plotyjs.

我已经测试了一些方法但没有成功!Julia 实现这一目标的正确方法是什么?

I have already tested some approaches with no success!What is a correct way in Julia to achive this?

推荐答案

可以广播getindex:

xs = getindex.(vv, 1)
ys = getindex.(vv, 2)

编辑 3:

或者,使用列表推导式:

Alternatively, use list comprehensions:

xs = [v[1] for v in vv]
ys = [v[2] for v in vv]

出于性能原因,您应该使用 StaticArrays 来表示 2D 点.例如:

For performance reasons, you should use StaticArrays to represent 2D points. E.g.:

getline(a,b) = [(1-i)a+(i*b) for i=0:0.1:1]

p1 = SVector(1.,2.)
p2 = SVector(3.,4.)

vv = getline(p1,p2)

广播getindex 和列表推导式仍然有效,但您也可以将向量重新解释2×11 矩阵:

Broadcasting getindex and list comprehensions will still work, but you can also reinterpret the vector as a 2×11 matrix:

to_matrix{T<:SVector}(a::Vector{T}) = reinterpret(eltype(T), a, (size(T,1), length(a)))

m = to_matrix(vv)

请注意,这不会复制数据.您可以简单地直接使用 m 或定义,例如,

Note that this does not copy the data. You can simply use m directly or define, e.g.,

xs = @view m[1,:]
ys = @view m[2,:]

编辑 2:

顺便说一句,不限制 getline 函数的参数类型有很多优点,通常是首选.上面的版本适用于任何使用标量和加法实现乘法的类型,例如,immutable Point ... end 的可能实现(不过,使其完全通用需要更多的工作).

Btw., not restricting the type of the arguments of the getline function has many advantages and is preferred in general. The version above will work for any type that implements multiplication with a scalar and addition, e.g., a possible implementation of immutable Point ... end (making it fully generic will require a bit more work, though).

这篇关于嵌套数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:38