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:
loop paralelization

Subject: loop paralelization

From: Michal Kvasnicka

Date: 4 Feb, 2013 14:12:08

Message: 1 of 3

Hello, I need to vectorize (to speedup code) the following loop:

[dim, n]=size(x);
A=zeros(n,n);
for i=1:n
    for j=1:i
        r=norm(x(:,i)-x(:,j));
        temp=feval(phi,r, const);
        A(i,j)=temp;
        A(j,i)=temp;
    end
end

where function "phi" is defined as
function u=phi(r, const)
u=exp(-0.5*r.*r/(const*const));

Any hints?

Subject: loop paralelization

From: dpb

Date: 4 Feb, 2013 15:46:25

Message: 2 of 3

On 2/4/2013 8:12 AM, Michal Kvasnicka wrote:
> Hello, I need to vectorize (to speedup code) the following loop:
>
> [dim, n]=size(x);
> A=zeros(n,n);
> for i=1:n
> for j=1:i
> r=norm(x(:,i)-x(:,j));
> temp=feval(phi,r, const);
> A(i,j)=temp;
> A(j,i)=temp;
> end
> end
>
> where function "phi" is defined as
> function u=phi(r, const)
> u=exp(-0.5*r.*r/(const*const));
>
> Any hints?

Most trivial first -- get rid of feval() and put the function evaluation
inline since it's so trivial. That'll help quite a bit I'd expect.

Second, since the diagonal is exp(0), no need to compute it; so run the
loop to i-1

May help some to only set the lower (or upper) block and then transpose
afterwards instead of in loop to augment...

I didn't think too much about the actual norm() part; I've got a meeting
to head to now but I'd think griddata() may help...

--

Subject: loop paralelization

From: Bruno Luong

Date: 4 Feb, 2013 18:02:08

Message: 3 of 3

"Michal Kvasnicka" wrote in message <keofjo$p85$1@newscl01ah.mathworks.com>...
> Hello, I need to vectorize (to speedup code) the following loop:
>
> [dim, n]=size(x);
> A=zeros(n,n);
> for i=1:n
> for j=1:i
> r=norm(x(:,i)-x(:,j));
> temp=feval(phi,r, const);
> A(i,j)=temp;
> A(j,i)=temp;
> end
> end
>
> where function "phi" is defined as
> function u=phi(r, const)
> u=exp(-0.5*r.*r/(const*const));
>
> Any hints?

x2 = x'*x;
d = diag(x2);
r2 = max(bsxfun(@plus,d,d')-2*x2,0);
c = -0.5/(const*const);
A = exp(c*r2)

% Bruno

Tags for 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