I'm struggling to speed up the code inside the version1 function. The only way to vectorize it that I can seem to figure out is version2, but that actually makes the function slower.
n1 = 400; n2 = 3; n3 = 7; n4 = 2; A = rand(n1, n2, n3); B = randi(n2, [n4, n1, n3]); disp(timeit(@() version1(A, B, C, n1, n2, n3, n4))); disp(timeit(@() version2(A, B, C, n1, n2, n3, n4))); function C = version1(A, B, n1, n2, n3, n4) C = zeros(n4, n1, n3); for ii = 1:n3 for jj = 1:n1 for kk = 1:n4 C(kk, jj, ii) = A( ... jj, ... B(kk, jj, ii), ... ii ... ); end end end end function C = version2(A, B, n1, n2, n3, n4) C = zeros(n4, n1, n3); for ii = 1:n3 for jj = 1:n1 C(:, jj, ii) = A( ... jj, ... B(:, jj, ii), ... ii ... ); end end end
[K,J,I]=ndgrid(1:n4,1:n1,1:n3); %Recycle this, if possible Bvals=B(sub2ind(size(B),K,J,I)); C=A( sub2ind(size(A), J,Bvals,I ));
Matlabsolutions.com provides guaranteed satisfaction with a
commitment to complete the work within time. Combined with our meticulous work ethics and extensive domain
experience, We are the ideal partner for all your homework/assignment needs. We pledge to provide 24*7 support
to dissolve all your academic doubts. We are composed of 300+ esteemed Matlab and other experts who have been
empanelled after extensive research and quality check.
Matlabsolutions.com provides undivided attention to each Matlab
assignment order with a methodical approach to solution. Our network span is not restricted to US, UK and Australia rather extends to countries like Singapore, Canada and UAE. Our Matlab assignment help services
include Image Processing Assignments, Electrical Engineering Assignments, Matlab homework help, Matlab Research Paper help, Matlab Simulink help. Get your work
done at the best price in industry.