Is this the right way to use permute and bsxfun?

3 views (last 30 days)
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]);

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 23 May 2023
Edited: Dyuman Joshi on 23 May 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

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!