Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

how i can remove the for statement from this program?

Asked by Ahmed almansory on 28 May 2013
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

0 Comments

Ahmed almansory

Products

No products are associated with this question.

2 Answers

Answer by David Sanchez on 28 May 2013
Accepted answer

you should initialize your n matrix to perform the assignment.

1 Comment

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
David Sanchez
Answer by 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.

0 Comments

Image Analyst

Contact us