arraysmatrixsumfortranfortran95

How to do SUM on array from outside file?


I'm newbie college student for programming studies, so recently i have task to calculate matrix from outside files for Gauss Jordan Numeric Method, in the txt file i provide has 10 (x) and (y) data, and declare with do functions to calculate the 10 data from the txt file each for x^2, x^3, x^4, xy, x^2y

my question is : how to SUM (calculate total) each x^2, x^3 ... that was calculated by program ? i try do sum file in below and still got errors (the first argument of sum must not a scalar.)

the Fortran apps i use was Plato cc from Silverfrost. I apologize if my english bad and my pogram looks funny.

i have 10 data in my txt looks like these :

(x)  (y)
12   10
5    6
28   8
9    11
20   17
6    24
32   9
2    7
1    30
26   22

in program below i open these files and want each x and y i provide read and calculate to get x^2, x^3, x^4, xy, x^2y

Program Gauss_Jordan
Real x(10),y(10),xj,yj,xj2,xj3,xj4,xjyj,xj2yj
 Open (10, file='Data.txt')
    Do j = 1,10
        Read(10,*) x(j), y(j)
        xj2 = x(j)**2
        xj3 = x(j)**3
        xj4 = x(j)**4
        xjyj = x(j)*y(j)
        xj2yj = (x(j)**2)*y(j)
            Do k = 1,10
            T(xj2) = SUM( xj2, dim=1)
            T(xj3) = SUM (xj3, dim=1)
            T(xj4) = SUM (xj4, dim=1)
            T(xjyj) = SUM (xjyj, dim=1)
            T(xj2yj) = SUM (xj2yj, dim=1)
            End Do
     End Do
 Close(10)
 End

for T(xj2) I want to get one result scalar result from SUM the all xj^2 that program has been calculated.

Like in excel was expected :

(A) is 1st xj^2 value that has been calculated
.
.
. 
until (J) is 10th xj^2 value that has been calculated
sxj^2 = SUM(Xj^2)
SUM (A-J)

Solution

  • The 'sum' intrinsic needs an array argument, which we can compute from the input arrays without using a loop, so your program could be:

    Program Gauss_Jordan
        Real x(10), y(10), x2(10), x3(10), x4(10), xy(10), x2y(10)
        Open(10, file='Data.txt')
        Do j = 1, 10
            Read (10, *) x(j), y(j)
        End Do
        Close(10)
        x2 = x**2
        x3 = x**3
        x4 = x**4
        xy = x*y
        x2y = (x**2)*y
        sx2 = SUM(x2)
        sx3 = SUM(x3)
        sx4 = SUM(x4)
        sxy = SUM(xy)
        sx2y = SUM(x2y)
    End