Clear Filters
Clear Filters

element-wise multiplication of lateral slices of a 3-D array with rows of a 2-D array in the 3rd dimension

1 view (last 30 days)
I am trying to find a compact way of multiplying lateral slices of a 3D array with rows of a 2D array where the mulitiplication is performed element-wise along the 3rd dimension (I think this is a correct description). I have vectorised the expressions as far as I can in several steps, but there are two residual loops that seem irreducible. I am curious if there is a way of further vectorizing this procedure to completely remove the for loops involving array columns, jj
% define some scalar constants
lam_y = 2.8749e-5; ep = 1.8e-3; Rf = 1; Dp = 3.6817e-4; G = 4.1964e-3; F = 5e4; tw = 1e2;
% define vectors corresponding to dimensions of final 3-D array
nx = 10; nz = 20; nt = 30; % assume an arbitrarily small grid for debugging purposes
xx = linspace(0,1,nx)'; zz = linspace(0,1,nz)'; t = linspace(0,1e5,nt)';
% calculate 2-D array del_t(nt,nx)
del_t = t - Rf*tw*xx';
del_t(del_t < 0) = 0;
% calculate 2-D arrays Fparmx(nz,nx) and arg1(nz,nx)
Fparmx = G*(F*xx' + zz./(ep*Dp));
arg1 = sqrt(lam_y)*Fparmx;
% calculate 3-D array arg2(nt,nx,nz) formed by multiplication of columns
% of del_t array with rows of Fparmx' array
for jj = 1:nx
arg2(:,jj,:) = 1./(2*sqrt(del_t(:,jj)))*[Fparmx(:,jj)]';
end
% calculate 3-D arrays arg3, E1 & E2
arg3 = repmat(sqrt(lam_y*del_t),[1 1 nz]); % arg3(nt,nx,nz)
E1 = erfc(arg2 - arg3); % E1(nt,nx,nz)
E2 = erfc(arg2 + arg3); % E2(nt,nx,nz)
% calculate 3-D array cp(nt,nx,nz) by multiplying lateral slices of E1 & E2 with
% tubes of reshaped array exp(±arg1) element-wise in the 3rd dimension
for jj = 1:nx
cp(:,jj,:) = 0.5*exp(-lam_y*Rf*tw*xx(jj))*...
(E1(:,jj,:).*reshape(exp(-arg1(:,jj)),1,1,[]) + ...
E2(:,jj,:).*reshape(exp(arg1(:,jj)),1,1,[]));
end

Accepted Answer

Aditya Srikar
Aditya Srikar on 28 Feb 2023
Hi James
I see that you want to reduce the number of statements and further optimize the code. But the code you have written is already optimised and further optimisation may not be required/possible.
  1 Comment
James
James on 28 Feb 2023
Thank-you for your answer Aditya! I was mostly curious whether it was possible (at least in in principal) to completely vectorize such as using arrayfunction or something like that. As you say, though the code is already as fast as it probably needs to be.

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!