how i can remove the for statement from this program?

1 view (last 30 days)
The basic idea is to divide an image into non-overlapping blocks and then convert each Block to column vector to become a column in the resulting matrix
The problem is:
1 - When you change the size of the block gives an error.
2 - Is it possible to replace loop statements with other statements which can reduce the overhead computation in program.
*********
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
% Read the image from disk.
m = imread('cameraman.tif');
[rows columns ] = size(m);
%prompt the user to input the size of rows & colums in block
prompt = {'Enter block row size:','Enter block column size:'};
dlg_title = 'Input size of the block';
num_lines = 1;
def = {'8','8'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
[val status] = str2num(answer{1});
%assign the user values to another variables
blockrow=val;
blockcolumn=val;
wholeBlockRows = floor(rows / blockrow);
blockVectorR = [blockrow * ones(1, wholeBlockRows), rem(rows, blockrow)];
wholeBlockCols = floor(columns / blockcolumn);
blockVectorC = [blockcolumn * ones(1, wholeBlockCols), rem(columns, blockcolumn)];
%convert the image into blocks
mCell = mat2cell(m, blockVectorR, blockVectorC);%now mCell contain all blocks
%convert each block to column vector then put the column vector as a column in new matrix n
t=1;
for i=1:rows/blockrow
for j=1:rows/blockrow
thisBlock = mCell{i,j};
columnVector = thisBlock(:);
n(:,t)=columnVector;
t=t+1;
end
end

Accepted Answer

David Sanchez
David Sanchez on 28 May 2013
you should initialize your n matrix to perform the assignment.
  1 Comment
David Sanchez
David Sanchez on 28 May 2013
t=1;
n = zeros(val*val);
for i=1:rows/blockrow
for j=1:rows/blockrow
thisBlock = mCell{i,j};
columnVector = thisBlock(:);
n(:,t)=columnVector;
t=t+1;
end
end

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 28 May 2013
Don't worry about it. Seriously -- don't worry about it. You're taking the advice against for loops to ridiculous extremes. No for loop that only executes a few dozen times is going to be speeded up enough for you to notice. Old-timers have even seen cases where vectorization ends up slower than for loops. If you want to improve your code your time would be better spent adding comments.

Categories

Find more on Convert Image Type 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!