Matrix/Array Increment Help

Hi, I have this problem.

I have a do and exit do condition. While the condition is true, I have a single dimension A matrix that will increase in size say A(1), A(1:2), …, A(1:i), …, A(1:i=n). Where the matrix shall be filled with increment number, say (0.5, 1, 1.5, 2).

The code will be like this:

i=0
do
if (condition is true)
i=i+1
something is done to matrix A
else if (condition is false)
cycle
else if (end condition is met)
exit
end if
end do

As you can see, at first (before end condition is met), we don’t know the size of matrix A and the content inside. Can anyone help me to explain what to do to matrix A.

Thank you in advance

1 Like

Hm, extending an array can be done like this:

real, allocatable :: a(:)

allocate( a(0) ) 
do i = 1,10
     a = [a, i*0.1] 
enddo
write(*,*) a

Does this at least partially answer your question?

2 Likes

There are many ways to address this situation. For example, if you always scan sequentially through the array (A(:) is an array, not a matrix), then perhaps a linked list is appropriate. If the array is indexed randomly but has some known maximum length, then maybe just allocating it to that maximum value but using some subset of those elements is appropriate. If there are only a few passes through the outer loop, then reallocating a new array inside the loop and copying the old elements might be appropriate (this is suggested above by Arjen). Maybe you can set up your conditional tests, but don’t do any work on the array, in order to determine its exact size, then allocate the array to that size, and then redo everything using that array and doing the actual work. All of these things can be done in fortran, the choice mostly depends on what exactly is the problem being solved.

2 Likes