如何在ADA中转置矩阵?我试过了:
procedure transpose(A: in out matrix) is
B : matrix(1..A'Last(2),1..A'Last(1));
begin
for i in A'Range(1) loop
for j in A'Range(2) loop
B(j,i):= A(i,j);
end loop;
end loop;
A := B;
end transpose;
但是当A不是方形矩阵时它不起作用。 任何帮助将不胜感激。
答案 0 :(得分:7)
作为一个过程,这对于非方形矩阵永远不会起作用,因为输出是与输入不同的约束类型。但是,您可以从适当的函数返回 B
。
function transpose(A: in matrix) return matrix is
B : matrix(A'Range(2),A'Range(1));
begin
for i in A'Range(1) loop
for j in A'Range(2) loop
B(j,i):= A(i,j);
end loop;
end loop;
return B;
end transpose;
为结果创建右约束类型矩阵的最简单方法是声明块:
declare
Transposed : Matrix := Transpose(A);
begin
-- operations on the transposed matrix
end;
答案 1 :(得分:1)
您可以通过创建如下记录来转置矩阵:
type Matrix_Type is record
Data : array (1..MAX_SIZE, 1..MAX_SIZE) of Float;
Last_Row : Positive range 1 .. MAX_SIZE;
Last_Column : Positive range 1 .. MAX_SIZE;
end record;
此记录可以支持任何m乘n大小的矩阵,最大n,m <= MAX_SIZE
您的程序变为:
procedure transpose(A: in out Matrix_Type) is
B : Matrix_Type;
begin
for i in 1..A.Last_Row loop
for j in 1..A.Last_Column loop
B(j,i):= A(i,j);
end loop;
end loop;
B.Last_Column := A.Last_Row;
B.Last_Row := A.Last_Column;
A := B;
end transpose;
答案 2 :(得分:0)
我所知道的最简单的方法是在中间数组类型上使用Fortran约定。 (这是因为Fortran惯例是列专业,而在Ada中,它是行专业。)
Function Transpose(M : Matrix) return Matrix is
subtype Constrained is Matrix(M'Range(2), M'Range(1));
Type Xposed is new Matrix with Convention => Fortran;
Temp : Xposed := Xposed(M);
Result : Constrained with Import, Address => Temp'Address; --'
begin
Return Result;
end Transpose;
答案 3 :(得分:0)
这是一个可行的示例:
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type matrix_array is array (Positive range<>, Positive range<>) of Float;
type matrix_array_ptr is access matrix_array;
function matrix_array_tranpose ( A: in matrix_array) return matrix_array_ptr is
A_t : matrix_array_ptr;
begin
A_t := new matrix_array(A'First(2)..A'Last(2),A'First(1)..A'Last(1));
for m in A'First(1)..A'Last(1) loop
for n in A'First(2)..A'Last(2) loop
A_t(n,m) := A(m,n);
end loop;
end loop;
return A_t;
end matrix_array_tranpose;
procedure matrix_array_print ( A: in matrix_array ) is
begin
for m in A'First(1)..A'Last(1) loop
for n in A'First(2)..A'Last(2) loop
Put(Float'Image(A(m,n)));
end loop;
Put_Line("");
end loop;
end matrix_array_print;
procedure matrix_array_print ( A: in matrix_array_ptr ) is
begin
for m in A'First(1)..A'Last(1) loop
for n in A'First(2)..A'Last(2) loop
Put(Float'Image(A(m,n)));
end loop;
Put_Line("");
end loop;
end matrix_array_print;
A : constant matrix_array :=
((5.0,7.0,-9.0),
(-11.0,13.0,15.0),
(-21.0,23.0,25.0));
A_t : matrix_array_ptr;
begin
Put_Line("A:");
matrix_array_print(A);
A_t := matrix_array_tranpose(A);
Put_Line("A_t:");
matrix_array_print(A_t);
end Main;