MATLAB: Error using subplot (line 301) Index exceeds number of subplots.

#errorsubplot #matlab #splitimage #blockimage

hi, guys..
i want to get the sub image of a gray scale image size 3081×4137. can i just do directly it by running the code that i saw in matlab ? fyi, i'm new to the matlab so i just try to run some code that has been created by some programmers in matlab to understand it.
actually i have tried it and i get error in 'sublot (2,2,sliceNumber)' when i run it in here :
for row = 1 : blockSizeR : rows
for col = 1 : blockSizeC : columns
row1 = row;
row2 = row1 + blockSizeR - 1;
row2 = min(rows, row2); % Don't let it go outside the image.

col1 = col;
col2 = col1 + blockSizeC - 1;
col2 = min(columns, col2); % Don't let it go outside the image.
% Extract out the block into a single subimage.
oneBlock = b(row1:row2, col1:col2);
% Specify the location for display of the image.
subplot(2, 2, sliceNumber);
imshow(oneBlock);
% Make the caption the block number.
caption = sprintf('Block #%d of 5', sliceNumber);
title(caption, 'FontSize', fontSize);
drawnow;*
what should i do, please ?

Best Answer

rowblocks = 1 : blockSizeR : rows;
colblocks = 1 : blockSizeC : columns;
numrowblocks = length(rowblocks);
numcolblocks = length(colblocks);
for rowidx = 1 : numrowblocks
row = rowblocks(rowidx);
for colidx = 1 : numcolblocks
col = colblocks(colidx);
row1 = row;
row2 = row1 + blockSizeR - 1;
row2 = min(rows, row2); % Don't let it go outside the image.

col1 = col;
col2 = col1 + blockSizeC - 1;
col2 = min(columns, col2); % Don't let it go outside the image.
% Extract out the block into a single subimage.
oneBlock = b(row1:row2, col1:col2);
% Specify the location for display of the image.
subplot(numrowblocks, numcolblocks, sliceNumber);
imshow(oneBlock);
% Make the caption the block number.
caption = sprintf('Block #%d of 5', sliceNumber);
title(caption, 'FontSize', fontSize);
drawnow;
end
end