我有两个复杂的载体:
a = [(0.5 + 2.0i), (-1.0 - 3.0i), (-3.0 + 1.5i)]
b = [(-0.5 - 2.2i), (1.3 + 2.0i), (3.0 - 2.5i)]
In Matlab, c = a.*b
也就是说,两个复杂向量的逐元素乘法给出了:
c = [(4.15 - 2.1i), (4.7 - 5.9i), (-5.25 + 12.0i)]
通常,在Swift中,我在单独的数组中表示复数向量的实部和虚部。
所以,
let aReal = [0.5, -1.0, -3.0]
let bReal = [-0.5, 1.3, 3.0]
let aImag = [2.0, -3.0, 1.5]
let bImag = [-2.2, 2.0, -2.5]
基于上面的乘法,在Swift中,我希望得到:
// cReal = [4.15, 4.7, -5.25]
// cImag = [-2.1, -5.9, 12.0]
答案 0 :(得分:2)
这取决于您使用这些内容做了什么,但我使用Complex
运算符定义了*
类型。例如在Swift 3中:
struct Complex<T: FloatingPoint> {
let real: T
let imaginary: T
static func +(lhs: Complex<T>, rhs: Complex<T>) -> Complex<T> {
return Complex(real: lhs.real + rhs.real, imaginary: lhs.imaginary + rhs.imaginary)
}
static func -(lhs: Complex<T>, rhs: Complex<T>) -> Complex<T> {
return Complex(real: lhs.real - rhs.real, imaginary: lhs.imaginary - rhs.imaginary)
}
static func *(lhs: Complex<T>, rhs: Complex<T>) -> Complex<T> {
return Complex(real: lhs.real * rhs.real - lhs.imaginary * rhs.imaginary,
imaginary: lhs.imaginary * rhs.real + lhs.real * rhs.imaginary)
}
}
// you can print it any way you want, but I'd probably do:
extension Complex: CustomStringConvertible {
var description: String {
switch (real, imaginary) {
case (_, 0):
return "\(real)"
case (0, _):
return "\(imaginary)i"
case (_, let b) where b < 0:
return "\(real) - \(abs(imaginary))i"
default:
return "\(real) + \(imaginary)i"
}
}
}
然后,您可以使用zip
和map
获取两个数组并使用两个数组中的相应值执行一些计算:
let a = [Complex<Double>(real: 0.5, imaginary: 2.0), Complex<Double>(real: -1.0, imaginary: -3.0), Complex<Double>(real: -3.0, imaginary: 1.5)]
let b = [Complex<Double>(real: -0.5, imaginary: -2.2), Complex<Double>(real: 1.3, imaginary: 2.0), Complex<Double>(real: 3.0, imaginary: -2.5)]
let c = zip(a, b).map { $0 * $1 }
print(c)
那会说:
[4.15 - 2.1i,4.7 - 5.9i,-5.25 + 12.0i]
或者,如果您确实拥有单独的数组,请先将它们转换为[Complex]
:
let aReal = [0.5, -1.0, -3.0]
let aImag = [2.0, -3.0, 1.5]
let bReal = [-0.5, 1.3, 3.0]
let bImag = [-2.2, 2.0, -2.5]
let a = zip(aReal, aImag).map { Complex<Double>(real: $0, imaginary: $1) }
let b = zip(bReal, bImag).map { Complex<Double>(real: $0, imaginary: $1) }
let c = zip(a, b).map { $0 * $1 }
print(c)