I have two arrays, and I want to compare their sizes and add trailing zeroes to whichever array is shorter.
eg- For arrays -
y1=(/ 1,2,3 /)
y2=(/ 1,2,3,4,5 /)
The final result should be -
y1=(/ 1,2,3,0,0 /)
y2=(/ 1,2,3,4,5 /)
I am very new to Fortran, and from what I know till now, this can be done like this:-
integer, allocatable :: y1(:),y2(:)
integer :: l1,l2,i
.
.
.
! some code to generate y1 and y2 here
.
.
.
l1=size(y1)
l2=size(y2)
if (l1>l2) then
do i=l2+1,l1
y2(i)=0
enddo
else if (l2>l1) then
do i=l1+1,l2
y1(i)=0
enddo
endif
I want to know if there is a better way of doing this, preferably one that doesn't involve loops, since the actual problem I am working on might have huge vectors
Here's one way:
y1 = RESHAPE(y1,SHAPE(y2),pad=[0])
No explicit loops. As @VladimirF commented the shorter array has to be re-allocated, this approach leaves it to the compiler and the run-time to take care of that.
If you are concerned about the performance of this approach, or concerned about its performance wrt a version using explicit loops, and concerned about how the performance scales with the sizes of arrays, then run some tests. I wouldn't be surprised to find that explicit reallocation and a loop or two are faster than this 'clever' approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With