【发布时间】:2016-08-26 00:23:51
【问题描述】:
我有一个 3 x 3 复数矩阵 c,因此我必须执行以下操作。 c 一般是复杂的,c 也可以更大,但它是一个方阵。
c= rand(3,3)
A = bsxfun(@mtimes,permute(reshape(reshape(permute(c(:,1:end~=2)',[2 1]),1,3*2).', 3, []),[3,1,2]),c(:,1))
conj(permute(A,[2 1 3]))
但是,时间太长了。哪个部分最耗时?
首先,c(:,1:end~=2)' 是没有第 2 列的矩阵的复共轭转置。
c = rand(3,3)
c =
0.9791 0.2003 0.9764
0.5933 0.2570 0.4920
0.5811 0.6384 0.9031
c(:,1:end~=2)'
ans =
0.9791 0.5933 0.5811
0.9764 0.4920 0.9031
其次,permute(c(:,1:end~=2)',[2 1]) 是一个让 reshape 按行工作的技巧。
permute(c(:,1:end~=2)',[2 1])
ans =
0.9791 0.9764
0.5933 0.4920
0.5811 0.9031
第三,做 reshape 和 .' 使其成为一个列:
reshape(permute(c(:,1:end~=2)',[2 1]),1,3*2).'
ans =
0.9791
0.5933
0.5811
0.9764
0.4920
0.9031
第四,将列重塑为 2 x 3 矩阵:
reshape(reshape(permute(c(:,1:end~=2)',[2 1]),1,3*2).', 3, [])
ans =
0.9791 0.9764
0.5933 0.4920
0.5811 0.9031
第五,创建一个多维数组,每一层都是列的行向量(只是重新排序,不采取复杂的共轭)。
permute(reshape(reshape(permute(c(:,1:end~=2)',[2 1]),1,3*2).', 3, []),[3,1,2])
ans(:,:,1) =
0.9791 0.5933 0.5811
ans(:,:,2) =
0.9764 0.4920 0.9031
六、用bsxfun得到c第一列与每一层的外积
bsxfun(@mtimes,permute(reshape(reshape(permute(c(:,1:end~=2)',[2 1]),1,3*2).', 3, []),[3,1,2]),c(:,1))
ans(:,:,1) =
0.9587 0.5809 0.5689
0.5809 0.3520 0.3448
0.5689 0.3448 0.3376
ans(:,:,2) =
0.9560 0.4817 0.8843
0.5793 0.2919 0.5359
0.5673 0.2859 0.5248
最后一个我认为不能简化。其目的是在每一层取矩阵的复共轭:
A = bsxfun(@mtimes,permute(reshape(reshape(permute(c(:,1:end~=2)',[2 1]),1,3*2).', 3, []),[3,1,2]),c(:,1))
A(:,:,1) =
0.9587 0.5809 0.5689
0.5809 0.3520 0.3448
0.5689 0.3448 0.3376
A(:,:,2) =
0.9560 0.4817 0.8843
0.5793 0.2919 0.5359
0.5673 0.2859 0.5248
conj(permute(A,[2 1 3]))
ans(:,:,1) =
0.9587 0.5809 0.5689
0.5809 0.3520 0.3448
0.5689 0.3448 0.3376
ans(:,:,2) =
0.9560 0.5793 0.5673
0.4817 0.2919 0.2859
0.8843 0.5359 0.5248
A(:,:,1) 是巧合对称的。
【问题讨论】:
-
代码中花费最多时间的是打印到命令窗口,因为您的语句没有以
;终止。 (我不是在开玩笑)