Using an array of indexes to index an array
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
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))));
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!