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:
Screenshot_20200525_151144

1 Like

Hi @ELNS,

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.

2 Likes

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.

3 Likes

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 ?

https://gcc.gnu.org/onlinedocs/gfortran/MATMUL.html

1 Like

Yes you’re right, I stand corrected.

1 Like

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

1 Like

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

1 Like

My mistake is in line number 6

Hi @ELNS,

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"
   else
      print *, "A and B have different shape"
   end if

Regards,

3 Likes