使用fortran生成可能组合的矩阵 [英] generate a matrix of possible combinations using fortran
问题描述
我有一个数组X(9,2),我想用所有可能的组合生成另一个数组B(512,9)。
我想过做9个循环,但我希望能有更高效的方式。
这是我有什么
do i1 = 1,2
do i2 = 1,2
do i3 = 1,2
do i4 = 1,2
do i5 = 1,2
do i6 = 1,2
do i7 = 1,2
do i8 = i,2
do i9 = 1,2
B(row,col)= X(1,i1)
col = col + 1
B(row,col)= X(2,i2)
col = col + 1
B(row,col)= X(3,i3)
col = col + 1
B )= X(4,i4)
col = col + 1
B(row,col)= X(5,i5)
col = col + 1
B(row,col)= X(6,i6)
col = col + 1
B(row,col)= X(7,i7)$ b (行,列)= X(8,i8)
col = col + 1
B(row,col)= X(9,i9)
col = 1
row = row + 1
end do
end do
end do
end do
end do
end do
end do
end do
end do
是这种方式有什么问题吗?有没有更好的方式来做到这一点?
谢谢!
你应该通过循环遍历B的元素,如下所示(我有一个print语句,而不是赋值...):
程序测试
隐式无
整数,参数:: nn = 9,imax = 2
整数::行,列,$
integer :: indices(nn)
indices(:) = 1
do row = 1,imax ** nn
do col = 1,nn
打印(A,I0,A,I0,A,I0,A,I0,A),B(,row,,,col,)= X(,&
& col,,indices(col),)
!B(row,col)= X(col,indices(col))
end do
indices(nn )=指数(nn)+ 1
ii = nn
同时(ii> 1.和指数(ii)> imax)
指数(ii)= 1
指数(ii-1)=指数(ii-1)+ 1
ii = ii - 1
结束做
结束做
结束程序测试
就我所见,这与原始代码的结果相同,但结构更紧凑,适用于任何元组大小和索引范围。 / p>
I have an array X(9,2) and I want to generate another array B(512,9) with all the possible combinations.
I thought about doing 9 do loops, but I was hoping for a more efficient way.
This is what I have
do i1=1, 2
do i2=1, 2
do i3=1,2
do i4=1,2
do i5=1,2
do i6=1,2
do i7=1,2
do i8=i,2
do i9=1,2
B(row, col) = X(1,i1)
col = col + 1
B(row, col) = X(2,i2)
col = col + 1
B(row, col) = X(3,i3)
col = col + 1
B(row, col) = X(4,i4)
col = col + 1
B(row, col) = X(5,i5)
col = col + 1
B(row, col) = X(6,i6)
col = col + 1
B(row, col) = X(7,i7)
col = col + 1
B(row, col) = X(8,i8)
col = col + 1
B(row, col) = X(9,i9)
col = 1
row = row + 1
end do
end do
end do
end do
end do
end do
end do
end do
end do
Is there something wrong with this way? Is there a better way of doing this?
Thanks!
You should make the loops the other way around by looping over the elements of B like the following (I have a print statement instead of the assignment...):
program test
implicit none
integer, parameter :: nn = 9, imax = 2
integer :: row, col, ii
integer :: indices(nn)
indices(:) = 1
do row = 1, imax**nn
do col = 1, nn
print "(A,I0,A,I0,A,I0,A,I0,A)", "B(", row, ",", col, ") = X(",&
& col, ",", indices(col), ")"
!B(row, col) = X(col, indices(col))
end do
indices(nn) = indices(nn) + 1
ii = nn
do while (ii > 1 .and. indices(ii) > imax)
indices(ii) = 1
indices(ii-1) = indices(ii-1) + 1
ii = ii - 1
end do
end do
end program test
As far as I can see, this gives the same result as your original code, but is by far more compact and works for any tuple sizes and index ranges.
这篇关于使用fortran生成可能组合的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!