使用向量索引多维 Fortran 数组 [英] Using a vector to index a multidimensional Fortran array

查看:42
本文介绍了使用向量索引多维 Fortran 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现代 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

是否有比编写 data(index(1), index(2), index(3) 更好(更通用)的方法来访问 data(4,6,9))?最好不要对 data 数组的等级进行硬编码.

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.

(天真地我想写 data(index) 但当然这实际上意味着不同的东西 - 子集收集" - 要求 data 是一个排名数组本身.)

(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.)

就其价值而言,这与 多维索引基本相同通过 JavaScript 中的索引数组,但在 Fortran 中.不幸的是,那里的聪明答案不适用于预定义的数组等级.

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.

推荐答案

没有.我能想到的所有解决方法都是可怕的黑客,你最好编写一个函数来将 dataindex 作为参数并吐出你的元素想要.

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

你可以定义一个rank-3指针

you can define a rank-3 pointer

double precision, pointer :: index_3d(:,:,:)

然后像这样设置:

index_3d(1:10,1:10,1:10) => data

嘿,快点,您现在可以在 data 中同时使用 rank-3 和 rank-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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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