-2

I have a data file with 2 columns. Let's say:
column 1 (8,8,8,6,9), reading it as a.
column 2 (3,4,5,6,7), reading it as b.
I want to write a code checking if a(i)=a(i+1) then b=0.

So result should be column 1 as a: (8,8,8,6,7), column 2 as b should be (0,0,0,6,7).

I tried this but failed:

program read2cols
  implicit none

  integer ::ios,i,j
  real a,b
  open(file='8081.txt', unit=22, status='old', action='read')

do 
   read(22,*,iostat=ios) a(i),b(j)
   if(a(i)<a(i))b=0 

       if(ios/=0) exit 
     print*,a,b 
 enddo
  close(22)


end program read2cols
  • 3
    What failed? Does it compile? Does it run? Does it produce an error message? Does it completes with an erroneous result? – Pierre de Buyl Dec 04 '18 at 11:40
  • 1
    Also: is this the *actual code that you have run*? Parts of your code make little sense and could lead to out-of-memory access and a runaway loop. – Pierre de Buyl Dec 04 '18 at 11:41
  • 1
    The way I read your question, `b(i) = 0` if `a(i) == a(i+1)`. But in that case, the resulting `b` should be `(0, 0, 5, 6, 7)`, as the 3rd value of `a` is different from the 4th. – chw21 Dec 04 '18 at 11:59
  • The more I look at the code, the more confused I get. `i` and `j` are never set, you are testing whether a value is smaller than itself, `a` and `b` are declared as variables, but most of the time they're addressed as arrays. – chw21 Dec 04 '18 at 12:05

1 Answers1

0

Your program can be something like this:

program read2cols
  implicit none

  integer :: ios, i, j
  real :: a(5), b(5)
  open(file='8081.txt', unit=22, status='old', action='read')

  read(22, *, iostat = ios) a(1), b(1)
  do i = 2,5
    read(22, *, iostat = ios) a(i), b(i)
    if (ios /= 0) exit
    if (a(i-1) == a(i)) b(i-1) = 0
  end do

  print *, a, b
  close(22)

end program read2cols

Output:

   8.00000000       8.00000000       8.00000000       6.00000000       9.00000000       
   0.00000000       0.00000000       5.00000000       6.00000000       7.00000000

Notes:

You declare a and b as scalars, then index through them using i, fix this by declaring a(5), b(5) as arrays. The loop index is missing in do .., it should read do i = ... Finally, the condition should be if (a(i-1) == a(i)) b(i-1) = 0 because you can compare a value only after it is read.

AboAmmar
  • 5,439
  • 2
  • 13
  • 24
  • In the code of the question, `a` and `b` are (external) functions, not scalars. – francescalus Dec 04 '18 at 15:30
  • The OP said: _column 1 (8,8,8,6,9), reading it as a. column 2 (3,4,5,6,7), reading it as b._, so definitely not external functions but arrays containing columns of numbers. – AboAmmar Dec 04 '18 at 15:32
  • The line `real a,b` declares `a` and `b` to be functions with return type real. Of course, we know this to be a mistake. – francescalus Dec 04 '18 at 15:33
  • @francescalus _A test for ios should probably be made before an attempt to reference the values a(i) and b(i)_, you're right about this. – AboAmmar Dec 04 '18 at 15:41