在Ocaml中转置矩阵可以通过以下步骤实现:
let create_matrix rows cols =
Array.init rows (fun _ -> Array.make cols 0)
let transpose_matrix matrix =
let rows = Array.length matrix in
let cols = Array.length matrix.(0) in
let transposed = create_matrix cols rows in
for i = 0 to rows - 1 do
for j = 0 to cols - 1 do
transposed.(j).(i) <- matrix.(i).(j)
done
done;
transposed
let print_matrix matrix =
let rows = Array.length matrix in
let cols = Array.length matrix.(0) in
for i = 0 to rows - 1 do
for j = 0 to cols - 1 do
print_int matrix.(i).(j);
print_string " "
done;
print_newline ()
done
现在可以使用这些函数来转置一个矩阵。以下是一个完整的示例:
let create_matrix rows cols =
Array.init rows (fun _ -> Array.make cols 0)
let transpose_matrix matrix =
let rows = Array.length matrix in
let cols = Array.length matrix.(0) in
let transposed = create_matrix cols rows in
for i = 0 to rows - 1 do
for j = 0 to cols - 1 do
transposed.(j).(i) <- matrix.(i).(j)
done
done;
transposed
let print_matrix matrix =
let rows = Array.length matrix in
let cols = Array.length matrix.(0) in
for i = 0 to rows - 1 do
for j = 0 to cols - 1 do
print_int matrix.(i).(j);
print_string " "
done;
print_newline ()
done
let () =
let matrix = create_matrix 3 4 in
matrix.(0) <- [|1; 2; 3; 4|];
matrix.(1) <- [|5; 6; 7; 8|];
matrix.(2) <- [|9; 10; 11; 12|];
let transposed = transpose_matrix matrix in
print_matrix transposed
这个示例创建了一个3行4列的矩阵,然后将其转置并打印出来。输出结果应该是:
1 5 9
2 6 10
3 7 11
4 8 12
这样就完成了在Ocaml中转置矩阵的操作。
领取专属 10元无门槛券
手把手带您无忧上云