用matlab语言写对矩阵进行cholesky分解的代码
时间: 2023-05-30 17:03:14 浏览: 58
function [L] = cholesky(A)
%CHOLESKY Cholesky decomposition of a positive definite matrix A.
% L = CHOLESKY(A) returns the lower triangular Cholesky factor L such that
% A = L*L', where A is a positive definite matrix.
% Check if A is a square matrix.
[m, n] = size(A);
if m ~= n
error('A must be a square matrix.');
end
% Check if A is a positive definite matrix.
if any(eig(A) <= 0)
error('A must be a positive definite matrix.');
end
% Initialize L.
L = zeros(n);
% Compute the Cholesky factorization.
for j = 1:n
for i = j:n
if i == j
L(i,j) = sqrt(A(i,j) - L(i,1:j-1).^2);
else
L(i,j) = (A(i,j) - L(i,1:j-1)*L(j,1:j-1)')/L(j,j);
end
end
end
end