MATLAB: “Reshaping” matrix

matrix manipulation

I have a matrix P_ind that is AxB (where each element is an integer in the range 1:C) and a matrix xgrid that is CxDxB. Is there a smart way to create a new matrix xgrid2 that is AxDxB without resorting to the for loop solution below?
xgrid2=NaN(A,D,B);
for i=1:A
for j=1:B
xgrid2(i,:,j)=xgrid(P_ind(i,j),:,j);
end
end
Edit: Since there were comments on the clarity of my question, let me try again. What I want to do is create the array xgrid2 in the code below, but in a more succint and most of all faster way than the nested for loops in my approach.
A=10000; % no. of individuals
B=65; % maximum age
C=30; % gridpoints for P
D=50; % gridpoints for S
P_ind=randi(C,A,B);
xgrid=randi(5000,A,D,B);
xgrid2=NaN(A,D,B);
for i=1:A
for j=1:B
xgrid2(i,:,j)=xgrid(P_ind(i,j),:,j);
end
end

Best Answer

Simpler and faster solution get rid of the outer loop:
xgrid3=NaN(A,D,B);
tic
for j=1:B
xgrid3(:,:,j)=xgrid(P_ind(:,j),:,j);
end
t2=toc
For me the time went from 3.1 second to 0.13 seconds.
Some performance concepts:
  • Not all for loops are bad
  • Try to not loop over the first indices of an array.
  • If you must loop over the first indices then make that loop the inner loop to traverse memory in the natural order.
  • Any solution that uses sub2ind is probably not optimal because of the extra work it must do and because it is rather slow.
Using sub2ind is a programming design trade-off because it may make the code easier to understand and debug.