Is it possible to use mldivide “\” on a 3D matrix in Matlab

旧时模样 提交于 2021-02-11 12:54:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!