help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Vectorizing a summation


From: Bård Skaflestad
Subject: Re: Vectorizing a summation
Date: Tue, 29 Jan 2013 15:40:43 +0100

On Tue, 2013-01-29 at 05:53 -0800, rdelgado wrote:
> I have a question about vectorizing a summation on Octave.
> 
> Suposse that I want to do this summation:
> 
> result = SUM(from i=1...MxN) SUM (from j=1...MxN) (Xi - Yi) * (Xj - Yj)

I don't get it.  Isn't this just

    sum(sum(X - Y)) ^ 2

?  Unless I'm grossly misinterpreting your statement, you appear to want
to vectorise the following calculation

    result = 0;
    for i = 1:prod(size(X)),
       for j = 1:prod(size(X)),
          result += (X(i) - Y(i)) * (X(j) - Y(j));
       end
    end

As the inner loop does not depend on 'i', this is equivalent to


    result = 0;
    MN = prod(size(X));
    for i = 1:MN,
       t = X(i) - Y(i);
       s = 0;
       for j = 1:MN,
          s += X(j) - Y(j);
       end
       result += t * s;
    end

which shortens to

    result = 0;
    s = sum(sum(X - Y));
    for i = 1:prod(size(X)),
       result += (X(i) - Y(j)) * s;
    end

which shortens to

    result = 0;
    s = sum(sum(X - Y));
    for j = 1:prod(size(X)),
       result += X(i) - Y(i);
    end
    result *= s;

which is

    result = sum(sum(X - Y)) ^ 2;


What am I missing?
-- 
Bård Skaflestad <address@hidden>



reply via email to

[Prev in Thread] Current Thread [Next in Thread]