problem with dividing matrix into subblocks using blockproc and global varaible!
Show older comments
Dear All, I want to divide a 3 by 15 matrix into 3 by 3 blocks (no overlap) blockproc. I use global variables to extract those blocks. Please have a look at this code shown below:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function test()
global all_blocks item
item=0; all_blocks=[];
x=rand(3,15)
fun = @(block_struct) block1(block_struct.data);
y = blockproc(x,[3 3],fun,'BorderSize',[0 0],...
'TrimBorder',true,'PadPartialBlocks',true);
z=all_blocks
end
function output= block1(in_array)
global all_blocks item
output=in_array;
item=item+1;
all_blocks{item}=in_array;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
the output of this code, z, is a 1 by 8 cells whereas the true output is 1 by 5 cells !. The cell no. 8, 7, and 6 of z are repeated (extra blocks). I do not want to use other functions such as mat2cell. Any suggestion why the output is like that?.. many thanks, wissam
3 Comments
Geoff Hayes
on 25 Apr 2014
Hi wissam,
I can't comment on why the code isn't working as intended (I don't have the blockproc command) but have you tried stepping through the code to see what is happening? Placing breakpoints at the update to all_blocks{item} may give you a clue as to why it is being updated with the additional three blocks.
Or an alternative to blockproc is to write the code yourself to extract the blocks (especially since you are not doing any sort of processing on the data other than to extract it from the matrix):
m = 3; % the number of rows in the block to extract
n = 3; % the number of columns in the block to extract
[r,c] = size(x); % get the number of rows and cols in x
rBlks = floor((r-1)/m) + 1; % determine the number of row blocks
cBlks = floor((c-1)/n) + 1; % determine the number of col blocks
z = cell(rBlks,cBlks); % size your output cell matrix
% extract all blocks from the matrix x
for i=1:rBlks
% determine the start row (xra) and the end row (xrb)
% for row block i
xra = (i-1)*m+1; xrb = min(xra+m-1,r);
for j=1:cBlks
% determine the start col (xca) and the end col (xcb)
% for column block j
xca = (j-1)*n+1; xcb = min(xca+n-1,c);
% reset the empty block to all zeros (zeros will be the
% padding in the event the block we extract from x is
% not complete)
blk = zeros(m,n);
% extract the data (which may now be padded)
blk(1:(xrb-xra+1),1:(xcb-xca+1)) = x(xra:xrb,xca:xcb);
% save to cell array
z{i,j} = blk;
end
end
Geoff
wissam
on 26 Apr 2014
Geoff Hayes
on 26 Apr 2014
I suspect that it will be relatively easy to add a 50% overlap…I will leave that for you though! :)
Answers (0)
Categories
Find more on Neighborhood and Block Processing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!