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

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

Mohammad Abouali
Mohammad Abouali il 10 Dic 2015
Modificato: Mohammad Abouali il 10 Dic 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.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by