       Re: Array from for-loop iterations

• To: mathgroup at smc.vnet.net
• Subject: [mg116885] Re: Array from for-loop iterations
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Thu, 3 Mar 2011 05:58:52 -0500 (EST)

```On 3/2/11 at 4:33 AM, lt648 at hszk.bme.hu (Lengyel Tamas) wrote:

>I am tackling a simple problem,

>I have written a simple for-loop using elements from an array of
>3-dimensional vectors:

>f0=0.5; For[k = 1, k < 9, k++,

>(vec[[k, 3]] - f0)^2 + (vec[[k, 1]] - f0) (vec[[k, 2]] - vec[[k,
>1]]) -
>vec[[k, 2]] - f0) (vec[[k, 3]] - f0)
>]

>I don't know how to make an array out of the computed results.

I assume what you want is the result of what is being computed
in the For loop. You have a computation but do not assign the
result to anything. Consequently, there is nothing to make an
array from. The return value from a For loop is Null.

If you insist on using a For loop, the value you want can be
obtained as follows:

generate some data:

In:= vec = RandomInteger[10, {8, 3}];

define an array for the result:

In:= res = Table[0, {9}];

Use a For loop to compute what you want:

In:= For[k = 1, k < 9, k++,
res[[k]] = (vec[[k, 3]] - f0)^2 + (vec[[k, 1]] - f0) (vec[[k,
2]] -
vec[[k, 1]]) vec[[k, 2]] - f0 (vec[[k, 3]] - f0)]

And now to see the result:

In:= res

Out= {0.,145.5,-22.5,-67.5,52.5,-52.5,-26.5,-73.5,0}

But an explicit loop isn't needed. That is the result can be
computed by doing:

In:= (vec[[All, 3]] - f0)^2 + (vec[[All, 1]] -
f0) (vec[[All, 2]] - vec[[All, 1]]) vec[[All, 2]] -
f0 (vec[[All, 3]] - f0)

Out= {0.,145.5,-22.5,-67.5,52.5,-52.5,-26.5,-73.5}

And when explicit loops are needed, it is almost always better
to use Table rather than For. You could use Table to do the
computation as follows:

In:= Table[(vec[[k, 3]] - f0)^2 + (vec[[k, 1]] -
f0) (vec[[k, 2]] - vec[[k, 1]]) vec[[k, 2]] -
f0 (vec[[k, 3]] - f0), {k, 8}]

Out= {0.,145.5,-22.5,-67.5,52.5,-52.5,-26.5,-73.5}

```

• Prev by Date: plot error messages are completelly missing
• Next by Date: Re: Vector Runge-Kutta ODE solver with compilation?
• Previous by thread: Re: Array from for-loop iterations
• Next by thread: How to suppress (hide) RunThrough window under Windows?