matlab - Filter elements from a 3D matrix without loop -
i have 3d matrix h(i,j,k)
dimensions (i=1:m,j=1:n,k=1:o)
. use simple case m=n=o = 2
:
h(:,:,1) =[1 2; 3 4]; h(:,:,2) =[5 6; 7 8];
i want filter matrix , project (m,n)
matrix selecting each j in 1:n
different k in 1:0
.
for instance, retrieve (j,k) = {(1,2), (2,1)}
, resulting in matrix g:
g = [5 2; 7 4];
this can achieved for
loop:
filter = [2 1]; % meaning filter (j,k) = {(1,2), (2,1)} = 1:length(filter) g(:,i) = squeeze(h(:,i,filter(i))); end
but i'm wondering if possible avoid for
loop via smart indexing.
you can create linear indices such output expansion needed first dimension bsxfun
. implementation -
szh = size(h) offset = (filter-1)*szh(1)*szh(2) + (0:numel(filter)-1)*szh(1) out = h(bsxfun(@plus,[1:szh(1)].',offset))
how work
(filter-1)*szh(1)*szh(2)
,(0:numel(filter)-1)*szh(1)
gets linear indices considering third , second dimension elements respectively. adding these 2 gives offset linear indices.add first dimenion linear indices
1:szh(1)
offset
array in elementwise fashionbsxfun
give actual linear indices, when indexedh
output.
sample run -
h(:,:,1) = 1 2 3 4 h(:,:,2) = 5 6 7 8 filter = 2 1 out = 5 2 7 4
Comments
Post a Comment