help-octave
[Top][All Lists]
Advanced

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

Re: help on calculating sum of combinations


From: pkienzle
Subject: Re: help on calculating sum of combinations
Date: Thu, 09 Oct 2003 00:58:22 +0100

On 8 Oct 2003 at 8:05, sanjiv kapur wrote:
> a function 
> from a matrix or an array,i want to calculate the sum of various 
> combinations, i.e
> if A=[2, 3, 4,5]
> how do i get
>       a1=2+3+4+5
>       a2=2*3+2*4+2*5+3*4+3*5+4*5
>       a3=2*3*4+2*3*5+2*4*5+3*4*5
>       a4=2*3*4*5

Here's a solution using the nchoosek function from octave-forge
(http://octave.sf.net):

function a=sumcomb(v)
  for k=length(v):-1:1
    a(k) = sum(prod(nchoosek(v,k),2));
  end
end


nchoosek itself is particularly inefficient (it uses a recursive
definition which expands to a complete matrix of all combinations)
so this solution recommends itself only for brevity, and not for
speed.

Paul Kienzle
address@hidden



-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.octave.org
How to fund new projects:  http://www.octave.org/funding.html
Subscription information:  http://www.octave.org/archive.html
-------------------------------------------------------------



reply via email to

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