如何通过 for 循环将矩阵记录到文本文件中,就像在 Julia REPL 中打印一样?

问题描述 投票:0回答:1

考虑以下循环:

julia> for i=1:3
         display(rand(2,2))
       end
2×2 Matrix{Float64}:
 0.338792  0.60386
 0.754133  0.357847
2×2 Matrix{Float64}:
 0.892743   0.728652
 0.0496951  0.44425
2×2 Matrix{Float64}:
 0.397286  0.779437
 0.311107  0.726685

我想将其记录到一个文本文件中,我在文本文件中的预期内容是:

2×2 Matrix{Float64}:
 0.338792  0.60386
 0.754133  0.357847
2×2 Matrix{Float64}:
 0.892743   0.728652
 0.0496951  0.44425
2×2 Matrix{Float64}:
 0.397286  0.779437
 0.311107  0.726685

请注意,

2×2 Matrix{Float64}:
部分也可以用空行替换。我试过:

julia> using DelimitedFiles

julia> for i=1:3
         mat = rand(2,2)
         display(mat)
         writedlm("output.txt", mat)
       end
2×2 Matrix{Float64}:
 0.451093  0.154907
 0.168872  0.955592
2×2 Matrix{Float64}:
 0.688501  0.451259
 0.984798  0.570832
2×2 Matrix{Float64}:
 0.697317   0.882904
 0.0414643  0.907534

但是结果是:

0.6973172179110919      0.8829040665300615
0.041464280519257546    0.9075339047610297
julia
1个回答
0
投票

以下方法有效:

julia> output_file = open("output.txt", "a+")
IOStream(<file output.txt>)

julia> for i = 1:3
           mat = rand(2, 2)
           display(mat)
           # Write the matrix header
           println(output_file, "2×2 Matrix{Float64}:")

           # Write the matrix row by row
           for row in 1:2
               println(output_file, join(mat[row, :], "\t"))
           end

           # Write a newline to separate matrices
           println(output_file)
       end
2×2 Matrix{Float64}:
 0.272009  0.495258
 0.585554  0.0147606
2×2 Matrix{Float64}:
 0.069176  0.577724
 0.301259  0.676222
2×2 Matrix{Float64}:
 0.534706  0.0833405
 0.502432  0.73081

julia> close(output_file)

文本文件包含:

2×2 Matrix{Float64}:
0.27200899396956457 0.49525783025976455
0.5855537125412538  0.014760621140570751

2×2 Matrix{Float64}:
0.06917603466304878 0.5777239290540206
0.30125883870640247 0.6762222223681158

2×2 Matrix{Float64}:
0.5347059926187145  0.08334051338144499
0.5024321091829739  0.7308095626114177


© www.soinside.com 2019 - 2024. All rights reserved.