Help needed vectorizing layer-wise 3d logical indexing problem.

1 view (last 30 days)
Hi folks,
I currently have a 3D logical array and a 2D matrix and I would like to logically index the 2D matrix using each layer of the logical array. I was wondering whether there was a faster, possibly more vectorized way that avoids a for loop.
eg.
A is p x q
B is p x q x r
C is cell(1,r)
for i = 1:r
C{i} = A(B(:,:,i));
end
Is there a one liner that can do this. My motivation is that I may want to parallelize this in the future.

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 10 Dec 2015
Edited: Mohammad Abouali on 10 Dec 2015
% Creating Sample A and B matrix
A=rand(3,4);
B= (rand(3,4,5))>0.5;
% one liner equivalent to your code.
C=mat2cell(A(mod(find(B)-1,numel(A))+1), ...
sum(reshape(B,[],size(B,3))))
You have to check though to see if it helps. Sometimes, looping is OK.

More Answers (0)

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!