how i can remove the for statement from this program?

1 次查看(过去 30 天)
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

采纳的回答

David Sanchez
David Sanchez 2013-5-28
you should initialize your n matrix to perform the assignment.
  1 个评论
David Sanchez
David Sanchez 2013-5-28
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

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2013-5-28
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.

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by