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

问题描述

我需要将一个数组乘以另一个元素逐个数组,就像数学中向量的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 multiplicationoperator directly as an argument to map instead of a closure expression:

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

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

08-29 13:25