Help me vectorize this code
1 次查看(过去 30 天)
显示 更早的评论
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
2 个评论
采纳的回答
Andrei Bobrov
2013-11-8
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));
更多回答(1 个)
Walter Roberson
2013-11-7
编辑:Andrei Bobrov
2013-11-8
[X, Y] = ndgrid(1:rows, 1:cols);
X = X(:);
Y = Y(:);
Z = reshape( bestori_map(1:rows,1:cols), [], 1);
linidx = sub2ind(size(RE), X,Y, Z);
RE_p(1:rows,1:cols ) = reshape(RE(linidx),rows, cols );
linidx = sub2ind(size(RO), X, Y, Z);
RO_p(1:rows,1:cols) = reshape(RO(linidx),rows, cols, );
Note: if RE and RO are the same size then you can re-use linidx instead of re-calculating it.
4 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!