MATLAB: How to use bsxfun or arrayfun to build the following matrix

arrayfunbsxfunfor loop

Hi, there.
I want to use bsxfun or arrayfun to replace the following for loop.
for s=1:S
New_P(s,:)=P(s,:,U0(s));
end;
for example,
if P(,,1)=[1,2;3,4];
P(:,:,2)=[5,6;7,8];
U0=[1;2];
then the final result is New_P=[1,2;7,8];
Thank you in advance!

Best Answer

Neither arrayfun nor bsxfun are useful for this. sub2ind is:
P = cat(3, [1 2;3 4], [5 6;7 8]);
U0 = [1;2];
New_P = P(sub2ind(size(P), ...
repmat((1:size(P, 1))', 1, size(P, 2)), ... rows where to pick the elements
repmat(1:size(P, 2), size(P, 1), 1), ... columns where to pick the elements
repmat(U0, 1, size(P, 2)))) %pages where to pick the elements