问题描述
是否有可能在现代Fortran语言使用矢量指数多维数组?也就是说,给定,也就是说,
Is it possible in modern Fortran to use a vector to index a multidimensional array? That is, given, say,
integer, dimension(3) :: index = [4,6,9]
double precision, dimension(10,10,10) :: data
有一个更好的(更普遍)的方式来访问数据(4,6,9)
不是写数据(指数(1)指数(2),指数(3))
?这将是很好不具有硬code中的数据军衔
阵列。
is there a better (more general) way to access data(4,6,9)
than writing data(index(1), index(2), index(3))
? It would be good not to have to hard-code the rank of the data
array.
(天真我想编写数据(指数)
但当然,这实际上意味着不同的东西 - 子聚会 - 要求数据
是一个秩一个阵列本身。)
(Naively I would like to write data(index)
but of course this actually means something different - subset "gathering" - requiring data
to be a rank-one array itself.)
有关它的价值,这是本质上的multidimensional在JavaScript的指数数组索引,但在Fortran语言来代替。不幸的是,聪明的答案,不会有与predefined阵列行列工作。
For what it's worth this is essentially the same question as multidimensional index by array of indices in JavaScript, but in Fortran instead. Unfortunately the clever answers there won't work with predefined array ranks.
推荐答案
没有。和所有我能想到的解决方法是可怕的黑客,你最好写一个函数取数据
和首页
作为参数,并吐出你想要的元素(S)。
No. And all the workarounds I can think of are ghastly hacks, you're better off writing a function to take data
and index
as arguments and spit out the element(s) you want.
您可能,但是,能够使用现代化的Fortran语言的能力为阵列级别重新映射到反其道而行之,这可能会满足你的愿望打的快和宽松与阵列的行列。
You might, however, be able to use modern Fortran's capabilities for array rank remapping to do exactly the opposite, which might satisfy your wish to play fast-and-loose with array ranks.
由于声明
double precision, dimension(1000), target :: data
您可以定义一个秩3指针
you can define a rank-3 pointer
double precision, pointer :: index_3d(:,:,:)
然后将其设置是这样的:
and then set it like this:
index_3d(1:10,1:10,1:10) => data
哎preSTO,现在可以同时使用秩3和秩1的指数纳入数据
,这是接近你想要做什么。我没有在愤怒中使用此还,但一些简单的测试,未发现任何严重问题。
and hey presto, you can now use both rank-3 and rank-1 indices into data
, which is close to what you want to do. I've not used this in anger yet, but a couple of simple tests haven't revealed any serious problems.
这篇关于Fortran语言:使用矢量索引多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!