Prod giving a different answer than repeated multiplication

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

KSSV
KSSV il 23 Giu 2021
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 Commenti
Divij Gupta
Divij Gupta il 23 Giu 2021
Thank you so much, that makes sense. What function can I use to vectorise matrix multiplication then?
Walter Roberson
Walter Roberson il 23 Giu 2021
Modificato: Walter Roberson il 23 Giu 2021
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)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by