如何按元素相乘两个数组 [英] How to multiply two arrays element-wise

查看:86
本文介绍了如何按元素相乘两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个数组乘以另一个数组元素,就像数学中向量的 Hadamard 乘积一样.例如:

I need to multiply an array by another array element-wise, just like the Hadamard product of vectors in math. For example:

A = [1,2,3,4]
B = [2,3,4,5]
C = A*B = [2,6,12,20]

我什至无法弄清楚代码,我已经尝试逐个元素地这样做,但这对我来说似乎太混乱了,有什么想法吗?

I can't even figure out the code, I've tried doing so element by element but this seems too messy of a solution for me, any ideas?

推荐答案

压缩"两个数组得到一个元组序列 (a_i, b_i)然后可以按元素相乘:

"Zipping" the two arrays gives a sequence of tuples (a_i, b_i) which can then be multiplied element-wise:

let A = [1,2,3,4]
let B = [2,3,4,5]

let C = zip(A, B).map { $0 * $1 }

print(C) // [2, 6, 12, 20]

(如果数组的长度不同,则 zip 会默默地忽略较长数组的额外元素.)

(If the arrays have different length then zip silently ignores the extra elements of the longer array.)

正如@appzYourLife 正确说的,你也可以通过乘法运算符直接作为 map 的参数而不是闭包表达式:

As @appzYourLife correctly said, you can also pass the multiplication operator directly as an argument to map instead of a closure expression:

let C = zip(A, B).map(*)

这篇关于如何按元素相乘两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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