问题
Is it possible to use mldivide
(\
) on a 3D matrix in MATLAB? I would like to avoid using a for loop?
Sample:
A = rand(4, 100, 5);
B = rand(4,4);
I need to perform:
C = B\A;
What I'm doing now:
Apply the mldivide on a for loop for each "slice" i:
for i = 1:size(A, 3)
C(:,:,i) = B \ A(:,:,i);
end
回答1:
You can reshape A
into a 2D matrix to perform the division and then back to the expected size afterwards. The reshape
operations should be relatively quick due to the fact that MATLAB doesn't alter the underlying data.
C = reshape(B \ reshape(A, size(A, 1), []), size(B, 1), size(A, 2), []);
And if we break that down:
%// Reshape A to be 4 x 500
Anew = reshape(A, size(A, 1), []);
%// Perform left division
C = B \ Anew;
%// Reshape C to be the expected size (4 x 100 x 5)
C = reshape(C, size(B, 1), size(A, 2), []);
This should work for any valid (size(A, 1) == size(B, 2)
) matrices A
and B
of any size.
来源:https://stackoverflow.com/questions/36579530/is-it-possible-to-use-mldivide-on-a-3d-matrix-in-matlab