嵌套数组切片 [英] Nested array slicing

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

问题描述

假设我有一个向量数组:

Let's say I have an array of vectors:

""" 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.

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

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)

或者,使用列表推导:

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和列表理解仍然可以,但是您也可以reinterpret将向量作为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,:]

顺便说一句,不限制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).

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆