Friday, February 1, 2019

arrays - MATLAB matrix element wise multiplication optimization

Given that the arrays in the input cell arrays are of identical sizes, it might be a better idea to have the inputs stored as multi-dimensional arrays instead of cell arrays to leverage MATLAB's vectorized techniques, which in this case would be indexing for extracting specific elements and matrix-multiplication for sum-reduction. So, when forming the inputs, we could look to form multi-dimensional arrays corresponding to the inputs : B_Container_Cell, C_Container_Cell, Coeff_x_Cell, Coeff_y_Cell and Coeff_z_Cell. Now, these are 1D cell arrays with B_Container_Cell containing 2D arrays and rest have 3D arrays. Thus, when using multi-dimensinal arrays, we would have them as one additional dimension, i.e. they would be 3D and 4D arrays respectively.


To simulate their multi-dimensional array formats, let's convert the given cell arrays with concatenation using cat along their last+1 dimension, like so -


Bm = cat(3,B_Container_Cell{:});
Cm = cat(4,C_Container_Cell{:});
Cx = cat(4,Coeff_x_Cell{:});
Cy = cat(4,Coeff_y_Cell{:});
Cz = cat(4,Coeff_z_Cell{:});

Finally, the vectorized solution to use these multi-dimensional arrays and get the desired outputs -


%// Get ACB across all iterations and reshaped into (Nx28) shaped array
Ar = reshape(bsxfun(@times,bsxfun(@times,Cm,permute(Bm,[1,2,4,3])),A_MAT),[],28);
%// Use matrix-multiplication to sum reduce sliced versions of Cx, Cy and
%// Cz, to get respectived summed outputs
sz = size(A_MAT); %// Output array size
Sum_x_out = reshape(Ar*reshape(Cx(p1,p2,:,:),[],1),sz);
Sum_y_out = reshape(Ar*reshape(Cy(p1,p2,:,:),[],1),sz);
Sum_z_out = reshape(Ar*reshape(Cz(p1,p2,:,:),[],1),sz);

Please note that it doesn't look like the parameter p3 was used.


Runtime test results (for listed sample inputs) -


--------------------------------- With Original Approach
Elapsed time is 2.412417 seconds.
--------------------------------- With Proposed Approach
Elapsed time is 1.572035 seconds.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...