Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to speed up this For-Loop by a vector?
Date: Fri, 13 May 2011 15:33:05 +0000 (UTC)
Organization: The Mitre Corp
Lines: 57
Message-ID: <iqjivh$f3j$1@newscl01ah.mathworks.com>
References: <iqjen4$pr$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-06-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1305300785 15475 172.30.248.38 (13 May 2011 15:33:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 13 May 2011 15:33:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2318
Xref: news.mathworks.com comp.soft-sys.matlab:726634

"Alex" wrote in message <iqjen4$pr$1@newscl01ah.mathworks.com>...
> Hi all,
> 
> i want to speed up a code, where i calculate a local standard deviation within another matrix.
> 
> e.g.:
> 
> mat1 = magic(100);
> mat2 = zeros(100,100);
> 
> for i = 8:93
>    for j = 8:93
>     mat2(i,j) = std2(i-7:i+7,j-7:j+7)
> 
>    end
> end
> 
> the code does exactly what i want, but is very slow. thats why im looking for a fast replacement.
> 
> i know how to adress the indices in a fast way an give them a fixed value
> (
> mat2(8:(size1-7),8:(size1-7)) = 5
> ) 
> 
> but i dont know how to make a fast, dynamic, calculation depending on the position.
> 
> hope you may help me
> 
> thanks a lot
> 
> alex

I don't have the Image Processing Toolbox, 
but the documentation says:

std2(A) computes the standard deviation of the array A using std(A(:))

If properly used (i.e., preallocation), for loops 
are not NECESSARILY slower than vectorized code.
(It depends on many factors such as size of arrays, available memory, etc.)
Aside frrom the obvious typo in the above code:
mat2(i,j) = std2(i-7:i+7,j-7:j+7)
should be (I assume something like):
mat2(i,j) = std2(mat1(i-7:i+7),mat1(j-7:j+7));  % note the semicolon at the end
You could try moving some calculations from 
from the inner loop to the outer loop 
(something like):

for i = 8:93
   mat3 = mat1((i-7:i+7);
   for j = 8:93
    mat4 = mat1(j-7:j+7);
    mat2(i,j) = std([mat3(:);mat4(:)]);  % note std instead of std2
   end
end

Just a thought