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:
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:
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.
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.
Do you obtain the same result with the MATMUL()
Fortran function ?
Yes you’re right, I stand corrected.
mt bad, i wrote A instead of B in do loop.
SOLVED!
I had seen nothing!
CTRL+C, CTRL+V =
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,