Monday, February 22, 2010

Double Summation in GNU Octave or Matlab

Let's say that you have two vectors: a n*1 vector t, and a N*1 vector T.

Let's say further, that you want to represent the double summation, equivalent to the following two for loops, without using loops, since Octave and Matlab suck at loops.

DoubleSum = 0;
for i = 1:n
  for j = 1:N
    DoubleSum += t(i) * T(j);
  end
end

Here's one possible method, using the intrinsic function sum.

DoubleSum = sum(sum((t * T')))

If you know some Octave, you will be able to parse the command by yourself.

Let's throw in another wrinkle. Let's say, that in addition to t and T, we had another N*1 vector g, and we wanted to find the double summation corresponding to the quantity g(j)*exp(-t(i)/T(j)), instead of t(i)*T(j) in the double for loop above.

Simple:

DoubleSum = sum(exp(-t * (1./T)') * g)

No comments: