Indexing a 4D array with a 2D matrix of indicies

旧街凉风 提交于 2019-12-20 01:40:02

问题


I currently have a 4D matrix of images in the form height x width x RGB x imageNumber in which I would like to index with a 2D array without using a for loop. The 2D array is in the format of height x width with the values being the image number to index.

I've got it working with A for loop but due to speed is there a way to do it without looping? I've tried resizing the matrix and index array but no luck so far.

Here is the for loop I've got working (albeit slowly on large images):

for height = 1:h
    for width = 1:w
        imageIndex = index(height, width);
        imageOutput(height, width, :) = matrix4D(height, width, :, imageIndex);
    end
end

where h and w are the height and width dimensions of the images.

Thank you!


回答1:


This uses implicit expansion to build a linear index that produces the desired result:

matrix4D = rand(4,2,3,5); % example matrix
[h, w, c, n] = size(matrix4D); % sizes
index = randi(n,h,w); % example index
ind = reshape(1:h*w,h,w) + reshape((0:c-1)*h*w,1,1,[]) + (index-1)*h*w*c; % linear index
imageOutput = matrix4D(ind); % desired result

For Matlab versions before R2016b you need to use bsxfun instead of implicit expansion:

ind = bsxfun(@plus, bsxfun(@plus, ...
    reshape(1:h*w,h,w), reshape((0:c-1)*h*w,1,1,[])), (index-1)*h*w*c); % linear index


来源:https://stackoverflow.com/questions/57649949/indexing-a-4d-array-with-a-2d-matrix-of-indicies

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!