0

i have a question about a loop inside a subroutine in fortran.

If i put this as subroutine, then i expect that the variable test becomes an array from 1 to 5.

p.s. type3 is defined as real, dimension(5,1)

subroutine build(test)
    type(typelist)     :: test
    do i = 1, 5
        test%type3(i)         = i 
end subroutine build

However this gives an error ;

    ||Error: Rank mismatch in array reference  (1/2)|

And when i remove the "(i)" after test%type3, it will work, but the result is 5.000 5.000 5.000 5.000 5.000. So it only assigns the value from the last loop to all entries in the array. And if i remove the %test the program does not know what type the variable test is anymore and it gives

 ||Error: Unclassifiable statement  |

Can someone tell me what i am doing wrong?

2
  • There is a tag for Fortran 90. You should make sure you use it in the future (and you don't need to mention language in the title). Commented Mar 24, 2014 at 18:05
  • This is an array rank broadcasting thing. type3 = i will set all array elements equal to i, which is why you get all 5s (the last do loop iteration overwrites previous ones). You can omit all array indices this way. But you can't just omit some (like one in a rank-2 array). You could do test%type3(i,:) = i (to broadcast over the last index) or test%type3(i,1) = i, but you can't just omit array indices - in general, there's no way to tell which ones you're leaving out. Commented Mar 24, 2014 at 18:12

1 Answer 1

2

Did you forget to assign with test%type3(i,1) = i?

Since type3 is a 2D array, you need two indices to assign values. When you type test%type3 = i you are assigning all elements at the same time with the same value. That is why in the end you get all 5.0.

PS. Where is the ENDDO statement?

Sign up to request clarification or add additional context in comments.

1 Comment

oh wow, that was it. I only had to turn the (i) into (i,1). Thanks a lot (and the end do statement was accidently fallen off when i removed all the pieces of code that were not relevant for this question)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.