Using an array of indexes to index an array

조회 수: 19 (최근 30일)
deltaruby
deltaruby 2019년 9월 7일
답변: Guillaume 2019년 9월 7일
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?

채택된 답변

Guillaume
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개)

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by