用2D索引矩阵索引4D数组 [英] Indexing a 4D array with a 2D matrix of indicies
问题描述
我目前有一个4D图像矩阵,其形式为高度x宽度x RGB x imageNumber,我想使用2D数组索引而不使用for循环. 2D数组的格式为高度x宽度,其值是要索引的图像编号.
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.
我已经将它与A for循环一起使用,但是由于速度原因,有一种方法可以不循环吗?我尝试过调整矩阵和索引数组的大小,但到目前为止还没有运气.
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.
这是我正在工作的for循环(尽管在大图像上慢慢显示):
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
其中h和w是图像的高度和宽度尺寸.
where h and w are the height and width dimensions of the images.
谢谢!
推荐答案
这使用线性索引,可产生所需的结果:
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
对于R2016b之前的Matlab版本,您需要使用 bsxfun
而不是隐式扩展:
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
这篇关于用2D索引矩阵索引4D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!