Re: basic issue with do and :=

• To: mathgroup at smc.vnet.net
• Subject: [mg60453] Re: basic issue with do and :=
• From: Bill Rowe <readnewsciv at earthlink.net>
• Date: Fri, 16 Sep 2005 03:51:02 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```On 9/15/05 at 5:16 AM, isolanoster at gmail.com (David) wrote:

>this works as (I) expected

>-------------------------
>Do[a[i] = i, {i, 10}]
>Do[b[i] =a[i]+1, {i, 10}]
>-------------------------

>While this doesn't:

>--------------------------
>Do[a[i] = i, {i, 10}]
>Do[b[i] :=a[i]+1, {i, 10}]
>---------------------------

>[note ":=" instead of "=" on the second line].

>namely the output is: "b[2]:=a[i]+1" for all i

>Is there any compact way to define: "b[i] :=a[i]+1" for all i ?

Yes. But before I give a specific suggestion, I have to wonder if you really understand what the code you say works as you expect is doing. I suspect you may be thinking a[i] refers to the ith element of an array named a. If so, that is quite wrong. The syntax a[i] refers to a function named a evaluated at i.

So, in the code that works as you expected the first Do loop defines values for the function a for evaluated at 1 through 10. The second Do loop defines values for a function named b for arguments 1 through 10. This is accomplished by evaluating the function a for each value of i (1 though 10) and adding 1 to the result. And since there already is a defined result for each of these values, definition for b is as you expect.

The difference in the code that doesn't work as you expect is the SetDelayed which causes i not to be evaluated in the expression a[i]. And since you've not defined a value for the function a at i, the result is the function b now has the value a[i]+1 for every value of i used to define b.

Now I can assume what you really intended was to create an array named a with pre-set values. If so, the better way to do that would be

a = Table[i, {i,10}]  or
a = Range[10]

Then doing simply b = a + 1 creates an array named b where every element is one greater than the corresponding element of array a.

But if you did understand the syntax a[i] to be the function named a evaluated at i and want a function b to have the value of a[i]+1 for every i from 1 to 10, that could be done as follows:

Do[a[i] = i, {i,10}];
b[i_]:= a[i] + 1
--
To reply via email subtract one hundred and four

```

• Prev by Date: Re: Bug in Reduce?
• Next by Date: Re: Batch
• Previous by thread: Re: basic issue with do and :=
• Next by thread: Strange error when using InequalityPlot3D