Pointwise multiplication of 3d array with 2d matrix and 1d array and summation by vectorization

5 次查看(过去 30 天)
I have a 2 by 2 matrix
A = rand(2,2)
and a 1 by 5 vector
v = [8 9 12 10 11];
I have a 3d array of dimension 2 by 2 by 5.
Call it D such that
D(:,:,1) = [1 2;3 4];
D(:,:,2) = [5 6;7 8];
D(:,:,3) = [12 11;10 9];
D(:,:,4) = [13 15;17 19];
D(:,:,5) = [21 22;23 28];
How can I do the operations of
J=zeros(2);
K=zeros(2);
for i = 1:5
J = J + D(:,:,i)'*A*D(:,:,i);
K = K + D(:,:,i)'*D(:,:,i);
end
and
Q = zeros(size(D));
for i = 1:5
Q(:,:,i) = v(i)*D(:,:,i);
end
by vectorization in the fastest way. I want to do it because the 3d array very huge dimension in general.

回答(1 个)

Stephen Jue
Stephen Jue 2016-8-31
编辑:Stephen Jue 2016-8-31
Hi Jeff,
These operations all require multi-dimensional matrix multiplication, which is not a built-in feature of MATLAB. However, there is a File Exchange function called mtimesx which can be used instead. It makes use of MATLAB's vectorization optimization by calling the "mtimes" function internally. It can do many operations to n-dimensional arrays, for example:
C = mtimesx(A,B) % performs the calculation C = A * B
C = mtimesx(A,'T',B) % performs the calculation C = A.' * B
C = mtimesx(A,B,'g') % performs the calculation C = A * conj(B)
C = mtimesx(A,'c',B,'C') % performs the calculation C = A' * B'
To calculate the sum (J = J + ...), you can use the result from "mtimesx" as an argument to cumsum.
Another alternative if you have the Parallel Computing Toolbox is to use the pagefun function.
I hope that helps.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by