Optimize 3D matrix indexing from vector and 2D matrix

1 view (last 30 days)
Hi all,
Might be a bit convoluted title, but I can explain best using an example. There must be a way to optimize this, but I can't figure out how. See the example loop below, basically I have the same issue twice. I don't know how to represent the [-1 0 1]+D(k,l) in matrix arithmetic.
K = 25;
L = 3000;
M = 250;
A = zeros(K,L,3);
B = zeros(K,L);
C = randn(K,L,M);
D = floor(3 + (M-3-1) .* rand(K,L)); % make sure that [-2:2]+D(k,l) is logical index
for k = 1:K
for l = 1:L
A(k,l,:) = reshape( C(k, l, [-1 0 1]+D(k,l)), [3 1] );
B(k,l) = sum( C(k, l, [-2:2]+D(k,l)) );
end
end
I'm interessted in an optimized variant of the above snippet. Are there any tricks I can do to get rid of the loop for this specific instance?

Answers (0)

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!