baibo
baibo

Reputation: 458

How to convert a loop into vector assignment notation

How would one go about converting a loop like this:

Do i = 2,101
   a(i) = b(i)
   c(i-1) = d(i) + d(i-1)
   d(i) = e(i) + 12
Enddo

in the vector notation of Fortran ? We can obviously split the loops, and do something like

a(2:101) = b(2:101)

but the last 2 statements depend on each other so that won't really work.

Upvotes: 2

Views: 180

Answers (3)

John Alexiou
John Alexiou

Reputation: 29244

OLD

Do i = 2,101
   a(i) = b(i)
   c(i-1) = d(i) + d(i-1)
   d(i) = e(i) + 12
Enddo

NEW

a(2:101) = b(2:101)
c(1:100) = d(2:101) + d(1:100)
d(2:101) = e(2:101) + 12

If this is any faster, I doubt it, and it may be more obscure as far as design intent is so vectorizing may not always be the best way to go.

EDIT 1

a(2:101) = b(2:101)
d(2:101) = e(2:101) + 12
c(1:100) = d(2:101) + d(1:100)

Since d depends on e only and c depends on d. From the loop above d(1) needs to have been defined earlier.

Upvotes: 1

Jeff Irwin
Jeff Irwin

Reputation: 1051

First of all, take a closer look at your un-vectorized loop. The first few iterations will look like this:

a(2) = b(2)
c(1) = d(2) + d(1)
d(2) = e(2) + 12

a(3) = b(3)
c(2) = d(3) + d(2)
d(3) = e(3) + 12

a(4) = b(4)
c(3) = d(4) + d(3)
d(4) = e(4) + 12

Unless d has been initialized earlier in the code, this could lead to unpredictable behavior (specifically, d(2) is used to calculate c(1) before d(2) itself is assigned).


EDIT: The rest of this post is incorrect, as pointed out by High Performance Mark. I'm leaving it here anyways for reference.

Note that c depends on d, but d does not depend on c. Thus, you could rewrite your code as follows:

a(2: 101) = b(2: 101)
d(2: 101) = e(2: 101) + 12
c(1: 100) = d(2: 101) + d(1: 100)

This is very similar to mtrw's answer, but note the + instead of - and the indices of c in the last line.

Upvotes: -1

mtrw
mtrw

Reputation: 35088

Jeff Irwin has the right idea by writing out a few iterations of the loop. c and d are updated as:

c(1) = d(2) + d(1)
d(2) = e(2) + 12

c(2) = d(3) + d(2) = d(3) + e(2) + 12
d(3) = e(3) + 12

c(3) = d(4) + d(3) = d(4) + e(3) + 12
d(4) = e(4) + 12

So, the Nth value of c depends on the N+1st value of d, and the Nth value of e. We can write the whole loop as:

a(2:101) = b(2:101)
c(1) = d(2) + d(1)
c(2:100) = d(3:101) + e(2:100) + 12
d(2:101) = e(2:101) + 12

Upvotes: 2

Related Questions