Using an array of indexes to index an array

24 views (last 30 days)
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?

Accepted Answer

Guillaume
Guillaume on 7 Sep 2019
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))));

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!