0

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. I.e 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.

1 Answer 1

4

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().

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

4 Comments

Wouldn't your method call maxloc twice?
Which method? Associate? No, it wouldn't.
Okay, I don't know enough about how associate works, and it'd be probably be optimised away anyway, but if not, wouldn't it call maxloc for each of the indices independently?
No, associates just stores the result of the expression into a temporary variable.

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.