arrays - Matlab: Remove loop from code -
flow
4d double matrix fourth dimension 2
. want implement loop without using loops.
essentially , each index in third dimension,, want divide flow1
square blocks of size block-size
, calculate mean of values in fourth dimension of each block, assign values respective fourth dimension elements in block .
typical values [height width n block_size] = [ 480 640 100 8]
. guaranteed block_size
factor of both height
, width
[height,width,n,~] = size(flow1); reduced_flow = zeros(size(flow1)); ii = 1:block_size:height jj = 1:block_size:width k = 1:n reduced_flow(ii:ii+block_size-1,jj:jj+block_size-1,k,1) = mean(mean(flow1(ii:ii+block_size-1,jj:jj+block_size-1,k,1),1),2); reduced_flow(ii:ii+block_size-1,jj:jj+block_size-1,k,2) = mean(mean(flow1(ii:ii+block_size-1,jj:jj+block_size-1,k,2),1),2); end end end
example
flow1 = round(10*rand(4,4,2,2)); block_size = 2; [flow1 reduced_flow] ans(:,:,1,1) = 6.0000 4.0000 1.0000 0 4.0000 4.0000 2.2500 2.2500 6.0000 0 2.0000 6.0000 4.0000 4.0000 2.2500 2.2500 0 5.0000 1.0000 3.0000 3.2500 3.2500 2.7500 2.7500 6.0000 2.0000 2.0000 5.0000 3.2500 3.2500 2.7500 2.7500 ans(:,:,2,1) = 7.0000 1.0000 3.0000 4.0000 4.5000 4.5000 2.7500 2.7500 5.0000 5.0000 2.0000 2.0000 4.5000 4.5000 2.7500 2.7500 5.0000 9.0000 6.0000 9.0000 6.7500 6.7500 5.5000 5.5000 4.0000 9.0000 6.0000 1.0000 6.7500 6.7500 5.5000 5.5000 ans(:,:,1,2) = 1.0000 9.0000 7.0000 5.0000 3.2500 3.2500 7.5000 7.5000 2.0000 1.0000 10.0000 8.0000 3.2500 3.2500 7.5000 7.5000 7.0000 10.0000 3.0000 8.0000 6.2500 6.2500 4.0000 4.0000 3.0000 5.0000 4.0000 1.0000 6.2500 6.2500 4.0000 4.0000 ans(:,:,2,2) = 2.0000 3.0000 7.0000 7.0000 2.7500 2.7500 6.5000 6.5000 4.0000 2.0000 5.0000 7.0000 2.7500 2.7500 6.5000 6.5000 1.0000 2.0000 9.0000 6.0000 4.2500 4.2500 4.5000 4.5000 5.0000 9.0000 1.0000 2.0000 4.2500 4.2500 4.5000 4.5000
approach 1
flow11 = reshape(flow1,size(flow1,1),[]); fun = @(block_struct) mean2(block_struct.data); mat1 = blockproc(flow11,[block_size block_size],fun); mat2 = imresize(mat1,block_size ,'nearest'); reduced_flow = reshape(mat2,size(flow1));
approach 2
t1 = sum(reshape(sum(reshape(flow1,block_size,[])),height/block_size,block_size,[]),2)./block_size^2; t2 = reshape(t1,1,1,[]); t3 = t2(ones(1,block_size),ones(1,block_size),:,:); t4 = reshape(permute(t3,[1 3 2]),size(t3,1)*size(t3,3),[]); out = permute(reshape(t4,height,size(t4,1)/height,[]),[1 3 2]); reduced_flow = reshape(out,size(flow1));
Comments
Post a Comment