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

Thread Subject:
speeding up a 'for loop' piece of code in Profiler

Subject: speeding up a 'for loop' piece of code in Profiler

From: Kate

Date: 7 Aug, 2013 01:19:17

Message: 1 of 4

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

Subject: speeding up a 'for loop' piece of code in Profiler

From: Roger Stafford

Date: 7 Aug, 2013 03:22:06

Message: 2 of 4

"Kate " <chino_tones@hotmail.com> wrote in message <kts7al$j41$1@newscl01ah.mathworks.com>...
> .........
> 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.
- - - - - - - - - - -
  Try replacing the contents of the for-loop with this:

 K = K + bsxfun(@minus,x(:,it_dim+1),x(:,it_dim+1)').^2;

or perhaps replace the entire for-loop and "zeros(m,m)" with this:

 K = bsxfun(@minus,x(:,2),x(:,2)').^2+bsxfun(@minus,x(:,3),x(:,3)').^2;

Roger Stafford

Subject: speeding up a 'for loop' piece of code in Profiler

From: Kate

Date: 7 Aug, 2013 03:37:06

Message: 3 of 4

thank you, roger

Subject: speeding up a 'for loop' piece of code in Profiler

From: Kate

Date: 8 Aug, 2013 01:36:10

Message: 4 of 4

Hi,

can anyone help me out in converting the original piece of code in my first post into MEX code? I would like to compare the speeds.

-cheers

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us