在Julia中将行添加到函数内部的矩阵中(并将更改传播到外部)? [英] Add a row to a matrix inside a function (and propagate the changes outside) in Julia?

查看:51
本文介绍了在Julia中将行添加到函数内部的矩阵中(并将更改传播到外部)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于以下问题:

在Julia中的矩阵中添加一行?

但是现在我想在一个函数中增加矩阵:

But now I want to grow the matrix inside a function:

function f(mat)
    mat = vcat(mat, [1 2 3])
end

现在,此功能之外:

mat = [2 3 4]
f(mat)

但这不起作用.在f内部对mat所做的更改不会传播到外部,因为在f内部创建了新的mat(请参见

But this doesn't work. The changes made to mat inside f aren't propagated outside, because a new mat was created inside f (see http://docs.julialang.org/en/release-0.4/manual/faq/#functions).

可以做我想做的事吗?

推荐答案

多维数组不能更改其大小.有指针黑客可以共享数据,但是这些确实可以不修改原始数组的大小.

Multi-dimensional arrays cannot have their size changed. There are pointer hacks to share data, but these do not modify the size of the original array.

即使有可能,请注意,因为Julia矩阵是列主矩阵,所以此操作非常慢,并且需要数组的副本.

Even if it were possible, be aware that because Julia matrices are column major, this operation is very slow, and requires a copy of the array.

在Julia中,修改传入数据的操作(即,对数据执行而不是对数据进行计算)通常用!标记.这向程序员表示正在处理的集合将被修改.这些类型的操作通常称为就地"操作,因为尽管它们难以使用和推理,但它们避免使用额外的内存,并且通常可以更快地完成.

In Julia, operations that modify the data passed in (i.e., performing computations on data instead of with data) are typically marked with !. This denotes to the programmer that the collection being processed will be modified. These kinds of operations are typically called "in-place" operations, because although they are harder to use and reason about, they avoid using additional memory, and can usually complete faster.

由于矩阵在内存中的存储方式,因此无法避免此操作的复制.因此,将该特定操作转换为就地操作并没有太大的实际好处.因此,我建议您反对.

There is no way to avoid a copy for this operation because of how matrices are stored in memory. So there is not much real benefit to turning this particular operation into an in-place operation. Therefore, I recommend against it.

如果出于某些原因确实需要此操作,则不应使用矩阵,而应使用向量的向量:

If you really need this operation for some reason, you should not use a matrix, but rather a vector of vectors:

v = Vector{Float64}[]
push!(v, [1.0, 2.0, 3.0])

此数据结构的访问速度稍慢,但添加时快很多.

This data structure is slightly slower to access, but much faster to add to.

从表面上看,您可能对更专业的数据结构感兴趣,例如

On the other hand, from what it sounds like, you may be interested in a more specialized data structure, such as a DataFrame.

这篇关于在Julia中将行添加到函数内部的矩阵中(并将更改传播到外部)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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