用2D索引矩阵索引4D数组

时间:2019-08-25 21:42:21

标签: arrays matlab 4d

我目前有一个4D图像矩阵,格式为高x宽x RGB x imageNumber,我想用2D数组索引而不使用for循环。 2D数组的格式为高度x宽度,其值是要索引的图像编号。

我已经将它与A for循环一起使用,但是由于速度原因,有没有一种方法可以不循环?我尝试过调整矩阵和索引数组的大小,但到目前为止还没有运气。

这是我正在工作的for循环(尽管在大图像上慢慢显示):

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

其中h和w是图像的高度和宽度尺寸。

谢谢!

1 个答案:

答案 0 :(得分:4)

这使用implicit expansion来构建产生所需结果的linear index

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而不是隐式扩展:

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
相关问题