我想写这种程序(这是一个简单的例子来解释我想做什么):
// #r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Math
// Definition of my products
let product1 = matrix [[0.;1.;0.]]
let product2 = matrix [[1.;1.;0.]]
let product3 = matrix [[1.;1.;1.]]
// Instead of this (i have hundreds of products) :
printfn "%A" product1
printfn "%A" product2
printfn "%A" product3
// I would like to do something like this (and it does not work):
for i = 1 to 3 do
printfn "%A" product&i
Run Code Online (Sandbox Code Playgroud)
先感谢您 !!!!!
Tom*_*cek 12
您可以使用矩阵列表,而不是为单个矩阵使用单独的变量:
let products = [ matrix [[0.;1.;0.]]
matrix [[1.;1.;0.]]
matrix [[1.;1.;1.]] ]
Run Code Online (Sandbox Code Playgroud)
如果您的矩阵是硬编码的(如您的示例所示),那么您可以使用上面的符号初始化列表.如果它们以某种方式计算(例如,作为对角线或排列或类似的东西),则可能有更好的方法来创建列表,使用List.init
或使用类似的功能.
一旦有了列表,就可以使用for
循环遍历它:
for product in products do
printfn "%A" product
Run Code Online (Sandbox Code Playgroud)
(在您的示例中,您没有使用索引进行任何操作 - 但如果由于某种原因需要建立索引,则可以使用[| ... |]
然后使用访问元素创建数组products.[i]
)