将矩阵打印到文件中 [英] Printing a matrix in to a file
问题描述
我需要在文件中打印DFGRD1(矩阵).我写了这些行
I need to print DFGRD1, a matrix, in a file. I have written these lines
open(105,file='C:\temp17\FM.mtx')
WRITE(105,*) DFGRD1
close(105)
c To check in .dat file
DO i=1,3
WRITE (7,*) (DFGRD1(i,j),j=1,3)
END DO
但是,答案并不相同.它们是彼此的换位.由于无法访问DFGRD1的实际值,因此我不知道哪个是正确的.如果有人可以帮助我,我将不胜感激.
However, the answers are not the same. They are the transpose of each other. Since I cannot access the real value of DFGRD1, I do not know which one is correct. I would really appreciate if someone could help me with it.
推荐答案
所有数组都存储在1d中,这只是内存布局的方式.
All arrays are stored in 1d -- that's just the way memory is laid out.
问题是它的存储方式. Fortran将其存储为主要列",即:
The question is how its stored. Fortran stores it as 'column-major', that is:
A(1, 1) -> A(2, 1) -> A(3, 1) -> A(1, 2) -> ... -> A(3, 3)
大多数其他语言存储的行主要数组,即
Most other languages store the arrays row-major, that is
A(1, 1) -> A(1, 2) -> A(1, 3) -> A(2, 1) -> ... -> A(3, 3)
(实际上,大多数语言默认情况下都从0开始索引.)
(In fact, most languages start indexing at 0 by default.)
因此,与通过循环遍历
So it's no surprise that you get different outputs when you write it in one go (where Fortran would store it the way it's laid out in memory) compared to when you specifically write it in row-major by looping over the j
index.
关于什么是正确的"-好的,这取决于您的代码.您只需要保持一致即可.
As for what is 'correct' -- well, that's up to your code. You just have to be consistent.
这篇关于将矩阵打印到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!