Using an array of indexes to index an array
16 次查看(过去 30 天)
显示 更早的评论
I have a 4D array containing a set of images, and a 2D array containing the indices of the 4th dim that will allow me to create an image based on the indices of the image in the 2D index array. One way i was able to do this was very slow but used the following code.
for rows = 1:imageSize(1)
for cols = 1:imageSize(2)
finalImage(rows,cols,:) = imageStack(rows,cols,:,indices(rows,cols));
end
end
Is there a faster way to do this in Matlab with matrix indexing?
0 个评论
采纳的回答
Guillaume
2019-9-7
Note that if you didnt' preallocate finalImage before the loop, your code will be slow indeed since finalImage would be reallocated and grown on each iteration.
The non-loop equivalent of your code:
[rows, cols, pages] = ndgrid(1:size(imageStack, 1), 1:size(imageStack, 2), 1:size(imageStack, 3));
finalImage = imageStack(sub2ind(size(imageStack), rows, cols, pages, repmat(indices, 1, 1, size(imageStack, 3))));
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!