将阵列数据读入不同大小的Fortran阵列 [英] Read in array data into different sized Fortran arrays

查看:86
本文介绍了将阵列数据读入不同大小的Fortran阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在文件array.txt中有一个5 x 5的浮点数组:

Let's say I have a 5 x 5 array of floating points in a file array.txt:

1.0 1.1 0.0 0.0 0.0
1.2 1.3 1.4 0.0 0.0
0.0 1.5 1.6 1.7 0.0
0.0 0.0 1.8 1.9 1.0
0.0 0.0 0.0 1.1 1.2

我知道这可能很奇怪,但是我只是想更好地学习read语句:我想在Fortran中创建两个3x3数组,即real, dimension(3,3) :: array1, array2并尝试在前9个中读取按行将这些值放入array1,并将随后的9个值放入array2.也就是说,我希望数组具有以下形式

I know this is probably a strange thing to do, but I'm just trying to learn the read statements better: I want to create two 3x3 arrays in Fortran, i.e. real, dimension(3,3) :: array1, array2 and try reading in the first 9 values by row into array1 and the following 9 values into array2. That is, I would like arrays to have the form

array1 = 1.0 1.1 0.0
         0.0 0.0 1.2
         1.3 1.4 0.0

array2 = 0.0 0.0 1.5
         1.6 1.7 0.0
         0.0 0.0 1.8

接下来,我想按列尝试执行相同操作:

Next I want to try to do the same by columns:

array1 = 1.0 1.2 0.0
         0.0 0.0 1.1
         1.3 1.5 0.0

array2 = 0.0 0.0 1.4
         1.6 1.8 0.0
         0.0 0.0 1.7

我的最接近"尝试逐行操作:

My "closest" attempt for row-wise:

program scratch
  implicit none

  real, dimension(3,3) :: array1, array2
  integer :: i

  open(12, file="array.txt")

 !read in values                                                 
  do i = 1,3
        read(12,'(3F4.1)', advance="no") array1(i,:)
  end do

end program scratch

我的问题:

A.结束时如何前进到下一条记录?

A. How to advance to next record when at the end?

B.读取列时该如何做?

B. How to do the same for reading in column-wise?

C.为什么需要'(3F4.1)',而不是'(3F3.1)'?

C. Why is '(3F4.1)' needed, as opposed to '(3F3.1)'?

推荐答案

由于需要按列分配",我建议将整个作品读入5x5数组:

because of the requirement to "assign by columns" i would advise reading the whole works into a 5x5 array:

 real tmp(5,5)
 read(unit,*)tmp

(请注意,不需要格式说明)

(note no format specification required)

然后使用数组操作完成所需的分配.

Then do the assignments you need using array operations.

对于这个小数组,最简单的操作似乎是:

for this small array, the simplest thing to do seems to be:

real tmp(5,5),flat(25),array1(3,3),array2(3,3)
read(unit,*)tmp
flat=reshape(tmp,shape(flat))
array1=reshape(flat(:9),shape(array1))
array2=reshape(flat(10:18),shape(array2))

然后转置的版本就是:

flat=reshape(transpose(tmp),shape(flat))
array1=reshape(flat(:9),shape(array1))
array2=reshape(flat(10:18),shape(array2))

如果这是一个非常大的数组,我会想到一种避免制作额外数据副本的方法.

If it was a really big array I'd think of a way that avoided making an extra copy of the data.

请注意,如果需要,您可以根据需要将所有这些分配包装在transpose中 您真正希望如何表示数据,例如.

Note you can wrap each of those assignments in transpose if needed depending on how you really want the data represented, eg.

     array1=transpose(reshape(flat(:9),shape(array1)))

这篇关于将阵列数据读入不同大小的Fortran阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆