简体   繁体   English

如何连接 Julia 中的两个向量?

[英]How to concatenate two vectors in Julia?

Given two vectors a = [1, 2] and b = [3, 4] , how do I obtain the concatenated vector c = [1, 2, 3, 4] ?给定两个向量a = [1, 2]b = [3, 4] ,我如何获得连接向量c = [1, 2, 3, 4] It seems that hcat or vcat could be used as they work on arrays, but when using vectors to store collections of elements it seems unfitting to first think about the orientation of the data;似乎可以使用hcatvcat ,因为它们在 arrays 上工作,但是当使用向量存储元素的 collections 时,首先考虑数据的方向似乎不合适; it's just supposed to be a list of values.它应该是一个值列表。

Most Array methods treat arrays as general "tensors" of arbitrary ranks ("data cubes"), so you do need to think about the orientation.大多数Array方法将 arrays 视为任意等级(“数据立方体”)的一般“张量”,因此您确实需要考虑方向。 In the general case, there's cat(a, b; dims) , of which hcat and vcat are special cases.一般情况下,有cat(a, b; dims) ,其中hcatvcat是特例。

There is another class of methods treating Vector s as list like.还有另一种方法 class 将Vector s 视为类似列表的方法。 From those, append!从那些, append! is the method that, well, appends a vector to another.是一种将向量附加到另一个向量的方法。 The problem is that it is mutable.问题是它是可变的。 So you can, for example, append,(copy(a), b) , or use something like BangBang.NoBang.append (which just selects the right method internally, though).例如,您可以使用append,(copy(a), b)或使用BangBang.NoBang.append之类的东西(不过,它只是在内部选择正确的方法)。

For the case of more than two vectors to be concatenated, I like the pattern of对于要连接的两个以上向量的情况,我喜欢以下模式

reduce(append!, (a, b), init=Int[])

You can write你可以写

[a; b]

Under the hood this is the same as vcat , but it's terser, looks better, and is easier to remember, as it's also consistent with literal matrix construction syntax.在底层,这与vcat相同,但它更简洁,看起来更好,并且更容易记住,因为它也与文字矩阵构造语法一致。

An alternative for concatenating multiple vectors is连接多个向量的另一种方法是

reduce(vcat, (a, b))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM