简体   繁体   English

将单线从 Numpy Python 转换为 Julia 涉及将一个二维数组映射到另一个二维数组

[英]Transform a one-liner from Numpy Python to Julia that involves mapping one 2D Array onto another 2D Array

Julia beginner here. Julia 初学者在这里。 I need to so some jugglery with a couple of matrices.我需要对几个矩阵进行一些杂耍。 My goal is as follows:我的目标如下:

Given a certain matrix Matrix1 as:给定一个矩阵 Matrix1 为:

在此处输入图像描述

, and a binary matrix Matrix2 as this: ,以及一个二进制矩阵 Matrix2,如下所示:

在此处输入图像描述

, I want to allocate the elements from Matrix1 to Matrix2 such that I have a final matrix Matrix3, which looks like: ,我想将元素从 Matrix1 分配给 Matrix2,这样我就有了一个最终的矩阵 Matrix3,它看起来像:

在此处输入图像描述

In Python, the following one liner worked:在 Python 中,以下一个班轮工作:

Matrix3= Matrix1.flatten()[(np.cumsum(Matrix2).reshape(Matrix2.shape)-1)] * Matrix2

Can anyone help me in writing a similar piece of code (preferably one liner if possible) in Julia?谁能帮我在 Julia 中写一段类似的代码(如果可能的话,最好是一行)?

Extension - I have gotten the answer for the above question from @cbk.扩展- 我从@cbk 得到了上述问题的答案。 As an extension to the question above.作为上述问题的延伸。 I was thinking of generalizing it for higher dimensional matrices.我正在考虑将其推广到更高维的矩阵。 So, suppose Matrix1 has dimension (4,6,6) and the binary matrix Matrix2 has dimension (4,12,12).因此,假设 Matrix1 的维度为 (4,6,6),二进制矩阵 Matrix2 的维度为 (4,12,12)。 The allocation problem remains the same.分配问题保持不变。 How would then you approach it?那你会怎么处理呢? Can someone kindly help me in it?有人可以帮我吗?

The main "gotchas" are that (1) you want to fill Matrix3 with the appropriate type of zero and (2) Julia is column-major, so you need to permute.主要的“陷阱”是(1)你想用适当的零类型填充 Matrix3 和(2)Julia 是列主要的,所以你需要置换。 This should do the trick though:不过,这应该可以解决问题:

(Matrix3 = zeros(eltype(Matrix1),size(Matrix2)))'[Matrix2'[:]].= Matrix1'[:]

A similar option would be类似的选择是

(Matrix3 = zeros(eltype(Matrix1),size(Matrix2)))'[vec(Matrix2')].= vec(Matrix1')

but this was slightly less efficient than the above, as measured by @btime但这比上面的效率略低,由@btime

edit: If Matrix2 originally contains integers instead of Booleans, you will need to convert before indexing with Matrix2 , eg:编辑:如果Matrix2最初包含整数而不是布尔值,则需要在使用Matrix2索引之前进行转换,例如:

(Matrix3 = zeros(eltype(Matrix1),size(Matrix2)))'[Bool.(Matrix2'[:])].= Matrix1'[:]

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

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