The following code give the identity matrix of any size the user wish it to be:
program identitymatrix
real, dimension(:, :), allocatable :: I
character:: fmt*8
integer :: ms, j
print*,'the size of the matrix is?'
read*,ms
allocate(I(ms,ms))
I = 0 ! Initialize the array.
forall(j = 1:ms) I(j,j) = 1 ! Set the diagonal.
! I is the identity matrix, let's show it:
write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'
! if you consider to have used the (row, col) convention,
! the following will print the transposed matrix (col, row)
! but I' = I, so it's not important here
write (*, fmt) I(:,:)
deallocate(I)
end program identitymatrix (the end of the code )
I am a bit confused about these two code pieces ?
write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'
write (*, fmt) I(:,:)
What does (A,I2,A)
do exactly?
Best Answer
'(A,I2,A)'
is a format specification; this one specifies a character field of sufficient length to hold the variable passed to it, followed by a 2-digit integer (field), followed by another character field which will be as long as the variable passed.This statement
uses that format specification to write another format specification into the character variable
fmt
. If, at run-time,ms
has the value4
,fmt
will become'(4F6.2)'
. This, in turn, is used to format the next write statement:This is the standard Fortran approach to creating output formats at run-time.