Is this the right way to use permute and bsxfun?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tanmay Agrawal
am 23 Mai 2023
Kommentiert: Tanmay Agrawal
am 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]);
0 Kommentare
Akzeptierte Antwort
Dyuman Joshi
am 23 Mai 2023
Bearbeitet: Dyuman Joshi
am 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)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!