# How to vectorize A\B operation on slices of 3D matrices?

3 views (last 30 days)
Jakub Tomasz Kaminski on 18 Mar 2021
Edited: Bruno Luong on 7 Apr 2021
Dear Matlab Users,
I am trying to solve a few separate sets of Ax = B equations with A\B or mldivide(A,B). A and B store equations components in their corresponding slices.
This is feasible with a for loop. Could it be done faster in some other way, with vectorization?
num_slices = 5;
A = rand(6,6, num_slices);
x = zeros(num_slices,6);
B = rand(6,1,num_slices);
% Working solution
for ii=1:num_slices
x(ii,:) =(A(:,:,ii)\B(:,:,ii))';
end
% Failed vectorization attempt
x_alternative =(A\B)'; % error here
The error I get is obvious as I do not use the "\" operation correctly:
Arguments must be 2-D, or at least one argument must be scalar. Use LDIVIDE (.\) for elementwise left division.
I would appreciate your help and suggestions in this matter.
EDIT:
I know about the option to flatten everything to sparse matices as suggested a few years ago here:
It would be great to learn if anything changed significantly from that time. Thank you!
Regards,
Jakub Kaminski
##### 2 CommentsShowHide 1 older comment
James Tursa on 7 Apr 2021
The ndfun code used to be here, but the links are now broken:
But I did find the source code here:

Bruno Luong on 18 Mar 2021
Edited: Bruno Luong on 18 Mar 2021
Yes there is new news since I post this MultipleQR fex (MEX required, OpenMP multithreading), for 6 x 6 this is the speed up on my LAPTOP, R2021a to solve one miillion linear systems A*x = y:
>> TestMultipleQRSolve
size(A) = [6 6 1000000]
size(y) = [6 1 1000000]
MultipleQRSolve time = 0.618821 [s]
Matlab loop time = 8.42263 [s]
For pure MATLAB sparse trick, you might be interested in my implementation of Multiple same size linear solver
Bruno Luong on 21 Mar 2021
I complete with the timings of the three methods
>> TestMultipleQRSolve
size(A) = [6 6 1000000]
size(y) = [6 1 1000000]
MultipleQRSolve time = 0.596974 [s]
Matlab loop time = 7.98282 [s]
SliceMultiSolver time = 2.56455 [s] % sparse trick

Jan on 18 Mar 2021
Edited: James Tursa on 7 Apr 2021
Do you have a compiler installed? Then use:
Bruno Luong on 7 Apr 2021
Benchmark with mmx('backslash', ...)
>> TestMultipleQRSolve
size(A) = [6 6 1000000]
size(y) = [6 1 1000000]
MultipleQRSolve time = 0.528698 [s]
Matlab loop time = 5.93315 [s]
SliceMultiSolver time = 1.8415 [s]
mmx(...) time = 0.369092 [s]