Ax,Ay,Az:[N×N]
B=AA(二元乘积)
它的意思是 :
B(i,j)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)]
B(i,j):一个 3x3 矩阵。构造 B 的一种方法是:
N=2;
Ax=rand(N); Ay=rand(N); Az=rand(N); %# [N-by-N]
t=1;
F=zeros(3,3,N^2);
for i=1:N
for j=1:N
F(:,:,t)= [Ax(i,j);Ay(i,j);Az(i,j)]*[Ax(i,j) Ay(i,j) Az(i,j)];
t=t+1; %# t is just a counter
end
end
%# then we can write
B = mat2cell(F,3,3,ones(N^2,1));
B = reshape(B,N,N)';
B = cell2mat(B);
当 N 很大时,有没有更快的方法。
编辑:
感谢您的回答。(更快)让我们说:N = 2; 斧头=[1 2;3 4]; Ay=[5 6;7 8]; 阿兹=[9 10;11 12];
B =
1 5 9 4 12 20
5 25 45 12 36 60
9 45 81 20 60 100
9 21 33 16 32 48
21 49 77 32 64 96
33 77 121 48 96 144
奔跑:
???错误使用 ==> mtimes 内部矩阵尺寸必须一致。
如果我写:P = Ai*Aj;
那么
B =
7 19 31 15 43 71
23 67 111 31 91 151
39 115 191 47 139 231
10 22 34 22 50 78
34 78 122 46 106 166
58 134 210 70 162 254
这与上面的 A(:,:,1) 不同,与 [Ax(1,1) Ay(1,1) Az(1,1)] 不同
编辑:
N=100;
Me :Elapsed time is 1.614244 seconds.
gnovice :Elapsed time is 0.056575 seconds.
N=200;
Me :Elapsed time is 6.044628 seconds.
gnovice :Elapsed time is 0.182455 seconds.
N=400;
Me :Elapsed time is 23.775540 seconds.
gnovice :Elapsed time is 0.756682 seconds.
Fast!
rwong: B was not the same.
编辑:
在对我的应用程序进行一些修改后:通过 gnovice 代码
1st code : 19.303310 seconds
2nd code: 23.128920 seconds
3rd code: 13.363585 seconds
似乎任何调用像 ceil,ind2sub ... 这样的函数都会使 thw 循环变慢,如果可能的话应该避免。
symIndex
很有趣!谢谢你。