MATLAB: Help me vectorize this code

codevectorize

for x=1:1:rows
for y=1:1:cols
RE_p(y,x) = RE(y,x,bestori_map(y,x));
RO_p(y,x) = RO(y,x,bestori_map(y,x));
end
end
– RE, RO: arrays of size cols*rows*8;
– bestori_map: array of size cols*rows;
what is the best way (and/or fastest) to vectorize this piece of code withouth the need of for cycles ?
Thank you

Best Answer

s = size(RE);
[ii,jj] = ndgrid(1:s(1),1:s(2));
ij = sub2ind(s,ii(:),jj(:),bestori_map(:));
RE_p = reshape(RE(ij),s(1:2));
RO_p = reshape(RO(ij),s(1:2));