[英]R .Fortran return reshaped array?
我正在探索將某些Fortran代碼實現到R中的情況。作為一個簡單的示例,我想創建一個簡單的Fortran文件來轉置R矩陣。 我知道.Fortran
僅會返回提交給它的參數。 考慮到這一點,我希望避免發送空白矩陣來容納新值,因為我希望將一些Fortran擴展到一些非常大的矩陣,這可能會導致R的開銷增加(如果我錯了,請糾正我。 )。 因此,我試圖轉置提交的矩陣並將其作為相同的參數返回。 我已經成功地在Fortran代碼中獲取了所需的輸出,但是無法使其在R中正確返回。您將在下面看到print語句返回適當的shape數組,但返回為'A'的數組仍然不正確。 我最初懷疑是與分配數組有關,但是當我嘗試實現時R一直崩潰。 任何見識將不勝感激。
測試f90
subroutine trans(A,n,m)
implicit none
integer, intent(in) :: n,m
double precision, intent(inout) :: A(n,m)
! declare local array to hold transpose
double precision :: B(m,n)
! do the transpose
B = transpose(A)
! try to reshape and reassign A
A = reshape(A, shape(B))
print*,A
end
編譯供R使用
R CMD SHLIB test.f90
R代碼
# or trans.so if on unix
dyn.load("test.dll")
# create simple matrix
set.seed(123)
a <- matrix(rnorm(15), 3, 5)
> a
[,1] [,2] [,3] [,4] [,5]
[1,] -0.5604756 0.07050839 0.4609162 -0.4456620 0.4007715
[2,] -0.2301775 0.12928774 -1.2650612 1.2240818 0.1106827
[3,] 1.5587083 1.71506499 -0.6868529 0.3598138 -0.5558411
# call fortran function
.Fortran("trans", a, as.integer(3), as.integer(5))
#output
>.Fortran("trans", a, as.integer(3), as.integer(5))
-0.56047565 -0.2301775 1.5587083
0.07050839 0.1292877 1.7150650
0.46091621 -1.2650612 -0.6868529
-0.44566197 1.2240818 0.3598138
0.40077145 0.1106827 -0.5558411
[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] -0.5604756 0.07050839 0.4609162 -0.4456620 0.4007715
[2,] -0.2301775 0.12928774 -1.2650612 1.2240818 0.1106827
[3,] 1.5587083 1.71506499 -0.6868529 0.3598138 -0.5558411
[[2]]
[1] 3
[[3]]
[1] 5
.Fortran
在列表中返回其輸出,其組成與參數相同。 所以你想做
a <- .Fortran("trans", a, 3L, 5L)[[1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.