       Re: Using "Sum" (i = 1 ... N) in a function definition

• To: mathgroup at smc.vnet.net
• Subject: [mg49704] Re: [mg49666] Using "Sum" (i = 1 ... N) in a function definition
• From: DrBob <drbob at bigfoot.com>
• Date: Thu, 29 Jul 2004 07:43:17 -0400 (EDT)
• References: <200407271100.HAA11129@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Clear[func]
data = {3, 2, 4, 5, 6}
func[i_] /; 1 <= i <= Length[data] := Tr[Take[data, i]]
{3, 2, 4, 5, 6}

func /@ Range
{3, 5, 9, 14, 20, func}

You can also make the dependence on "data" explicit in various ways (highly recommended). For instance,

ClearAll@func
data={3,2,4,5,6};
func[data_List][i_Integer]/;1â?¤iâ?¤Length[data]:=Tr[Take[data,i]]

func[data]/@Range

{3,5,9,14,20,func[{3,2,4,5,6}]}

Bobby

On Tue, 27 Jul 2004 07:00:44 -0400 (EDT), Rainer <wilhelm.rainer at gmx.net> wrote:

> I was trying to define a function using the Sum command in the
> following way (simplified example):
>
>  MyData = {3,2,4,5,6};
>  MyFunc[i_] = Sum[MyData[[j]],{j,1,i}];
>
> As you can see, the idea is to use the length of the list (i)
> as a variable in the function definition, such that
>
>  MyFunc = 3
>  MyFunc = 3 + 2 = 5
>  MyFunc = 3 + 2 + 4 = 9
>
> etc. Mathematica does not like the abobe statements, and prints the
> following error message:
>
> "Part specification K\$394 is neither an integer nor a list of
> integers."
>
> Does anybody know how to define (correctly) such a function. Should be
> possible ...?
> Thanks
> Rainer
>
>
>

--
DrBob at bigfoot.com
www.eclecticdreams.net

```

• Prev by Date: Re: Re: DeleteCases : several at once, conditions
• Next by Date: Re: graphs and top most nodes
• Previous by thread: Re: Using "Sum" (i = 1 ... N) in a function definition
• Next by thread: Re: Using "Sum" (i = 1 ... N) in a function definition