在 MATLAB 中,可以使用 rand 函数生成随机数组,使用 linsolve 函数求解线性方程组 Ax = b。
下面是一个例子:
function e = solveLinearSystem(n)
% 生成随机矩阵 A 和向量 b
A = rand(n, n);
b = rand(n, 1);
% 求解线性方程组 Ax = b
x = linsolve(A, b);
% 计算残差 r = Ax - b
r = A * x - b;
% 计算残差的范数,并输出作为误差 e
e = norm(r);