简体   繁体   中英

Array access through a list

My question is more of a quest for confirmation that the conclusions I have drawn are correct and to see if anyone has any smart "work-arounds".

My problems starts with a friend wanting to use maxloc to extract the location of the maximum value of an array and then use this result to read a corresponding element of an other array. Ie in pseudo code:

c = b(maxloc(a))

This however returns the error

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

(He is working with (N,N) arrays.)

I did some tests and I found that this does indeed not work. My conclusion is that you need to do something like this:

program h
    integer :: a(2,2)
    integer :: id(2),id2(2)
    a(1,1) = 1; a(1,2) = 2;  a(2,1) = 3;  a(2,2) = 2
    id = maxloc(a)
    write(*,*) a(id(1),id(2))
end program h

It works and everyone is happy. Well, except me. I want to know if there is a better way of doing it. Is there something I am missing? An easy solution to the problem.

Yes, that is correct, maxloc returns an array (sort of a vector of indexes) and you cannot use it for multidimensional array indexing. Vector indexing does something else and is mostly used for 1-D arrays.

You can use maxval() to get the maximum value of the array directly, but that may not be the thing you need in all cases.

You can also use associate and avoid declaring a new variable in the scope:

associate(id => maxloc(a))
  write(*,*) a(id(1),id(2))
end associate

but that will be more useful if your use is more complicated and cannot be just done by maxval() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM