Is this the right way to use permute and bsxfun?

3 vues (au cours des 30 derniers jours)
Tanmay Agrawal
Tanmay Agrawal le 23 Mai 2023
Commenté : Tanmay Agrawal le 23 Mai 2023
Hi all,
I have two matrices A and B where the size of A is 1000 x 200 x 500 (i x j x k in Cartesian notation) and that of B is 1000 x 500.
What I want to achieve is a matrix C such that C is also the same size as A and every jth column of C is obtained by subtracting the matrix B from the corresponding column of A. In this regard, is the following code correct? Since it is a 3D system, I am not able to verify it very easily.
C = permute(bsxfun(@minus, permute(A, [1 3 2]), B), [1 3 2]);

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 23 Mai 2023
Modifié(e) : Dyuman Joshi le 23 Mai 2023
Yes, it is correct. You can verify it by comparing it to the result obtained via loops -
%Random data
A = rand(1000,200,500);
B = rand(1000,500);
%Original code
C1 = permute(bsxfun(@minus, permute(A, [1 3 2]), B), [1 3 2]);
%Loop method
C2 = zeros(size(A));
for jdx = 1:size(A,2)
C2(:,jdx,:) = reshape(A(:,jdx,:),size(B)) - B;
end
isequal(C1,C2)
ans = logical
1

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by