Path: news.mathworks.com!not-for-mail
From: "Kate " <chino_tones@hotmail.com>
Newsgroups: comp.soft-sys.matlab
Subject: speeding up a 'for loop' piece of code in Profiler
Date: Wed, 7 Aug 2013 01:19:17 +0000 (UTC)
Organization: cbvzdfg
Lines: 38
Message-ID: <kts7al$j41$1@newscl01ah.mathworks.com>
Reply-To: "Kate " <chino_tones@hotmail.com>
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 1375838357 19585 172.30.248.38 (7 Aug 2013 01:19:17 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 7 Aug 2013 01:19:17 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2464542
Xref: news.mathworks.com comp.soft-sys.matlab:800523

hello all,

My code is as follows:


 clc;clear all

%----generate data----%
[X,Y] = meshgrid(-50:2:50, -50:2:50);                                
Z = X .* exp(-X.^2 - Y.^2);                                        
X= X(:);
Y = Y(:);
Z =Z(:);
x = [X Y Z];
%---------------------%


%----- run computation -----%
[m, M] = size (x);
dim    = M  - 1;

K= zeros (m,m);

for it_dim=1:dim
  tmp = x(:,it_dim+1) * ones(1,m) - ones(m,1) * x(:,it_dim+1)';
  tmp = tmp .* tmp;
  K = K + tmp;
end;
%---------------------------%


In the 'run computation' part, the FOR loop uses a variable 'tmp'. When I run the entire code in Profiler, the following line within the FOR loop takes the longest time :

  tmp = x(:,it_dim+1) * ones(1,m) - ones(m,1) * x(:,it_dim+1)';

Can anyone suggest a way to perhaps code it more efficiently for less time consumption.

-cheers