Prod giving a different answer than repeated multiplication

1 次查看(过去 30 天)
X(:,:,1) = [0.0000 + 0.0000i 0.0000 + 0.0000i 1.0000 + 0.0000i 0.0000 + 0.0000i;0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 1.0000 + 0.0000i;1.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i;0.0000 + 0.0000i 1.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i];
X(:,:,2) = [0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 - 1.0000i 0.0000 + 0.0000i;0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 - 1.0000i;0.0000 + 1.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i;0.0000 + 0.0000i 0.0000 + 1.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i];
X(:,:,3) = [0.0000 + 0.0000i 1.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i;1.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i;0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i -1.0000 + 0.0000i;0.0000 + 0.0000i 0.0000 + 0.0000i -1.0000 + 0.0000i 0.0000 + 0.0000i];
X(:,:,4) = [0.0000 + 0.0000i 0.0000 - 1.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i;0.0000 + 1.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i;0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 + 1.0000i;0.0000 + 0.0000i 0.0000 + 0.0000i 0.0000 - 1.0000i 0.0000 + 0.0000i];
I have the given 3D array. For some reason prod(X(:,:,1:4),3) gives 0 as the output. That does not match with the output for X(:,:,1)*...X(:,:,4). I do not want to use a loop, I want to use a vectorised method. However, prod is giving me issues. Am I doing something wrong? Is there another method?

采纳的回答

KSSV
KSSV 2021-6-23
prod gives you element by element multiplication.
Check:
A = rand(2,2,3) ;
X = prod(A,3) ;
Y = A(:,:,1).*A(:,:,2).*A(:,:,3) ; % element by element mulltiplication
Z = A(:,:,1)*A(:,:,2)*A(:,:,3) ;
isequal(X,Y)
ans = logical
1
isequal(X,Z)
ans = logical
0
  2 个评论
Divij Gupta
Divij Gupta 2021-6-23
Thank you so much, that makes sense. What function can I use to vectorise matrix multiplication then?
Walter Roberson
Walter Roberson 2021-6-23
编辑:Walter Roberson 2021-6-23
You cannot vectorize matrix multiplication.
You can make the process a little more compact by using fold() https://www.mathworks.com/help/symbolic/fold.html . However that requires the Symbolic Toolbox
The elements you would implicitly loop over would be created by using num2cell(A,3)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by