Comparing two 2D arrays

Hi all,
I am gonna implement a matrix product program in fortran and i have to compare shape of two given arrays. I wrote code below:

But i got this error:

1 Like


The error message is simply saying that you are trying to store a 1D array in a scalar variable.
This is because the shape intrinsic function returns a 1D array with as many elements as dimensions of the input.
See here.

In your example, A and B are two-dimensional arrays, so shape will return a 1D array of length 2.
Therefore shape_A and shape_B should be declared as 1D arrays of length 2.
Also note that array dimensions are always integers, so shape_A and shape_B should be declared as integer arrays:

integer, dimension(2) :: shape_A, shape_B

This latter point is important since you can’t strictly test for equality (==) between real numbers, as in your example, only between integers.

Finally, you will probably need to use the all intrinsic function in your comparison, e.g.:

if (all(shape_a == shape_b)) then

which returns .true. if all elements of shape_A and shape_B are equal.
Hope that helps.


Thank you very much @lkedward

Just a caution here, this is not generally true. I agree that in this case, @ELNS wants integer variables and equality test. I think what you mean is that often the result of a floating point equality test is not what the user expects.

However, there are use cases where testing for floating point equality is exactly what you want. In my field, this is usually for bit-for-bit reproducibility, i.e. testing that the code is deterministic. For example, testing that a procedure returns exactly the same output every time it’s run with same inputs. Or, that a procedure returns the same output when running on different number of parallel processes.

There may be many more use cases that I don’t know of.


This is the current status of my program:

that returns 0.0 for all elements of C. Any ideas? :thinking: :thinking:

Do you obtain the same result with the MATMUL() Fortran function ?

1 Like

Yes you’re right, I stand corrected.

1 Like

mt bad, i wrote A instead of B in do loop.

1 Like

I had seen nothing!
CTRL+C, CTRL+V = :bomb:

1 Like

My mistake is in line number 6


Also, to get closer to the “ideal” of “For(mula)Tran(slation)”, you can consider doing away with local variables and let the processor (compiler in ordinary speak) do most of the work with what are effectively temporary objects:

   if ( all( shape(A) == shape(B) ) ) then
      print *, "A and B have same shape"
      print *, "A and B have different shape"
   end if