Need MATLAB code Part 1 (25 pts) Write a MATLAB function of the form [L,U, P, D]
ID: 3761221 • Letter: N
Question
Need MATLAB code
Part 1 (25 pts) Write a MATLAB function of the form [L,U, P, D]= get_lu (A) that accepts a square matrix A and returns the LU or LDU decomposition of A with the permutation matrix P. Output argument D is optional when calling get_lu. If D is omitted in the function call, then the LU decomposition is performed, and nothing is returned in D. If D is included in the function call, then the LDU decomposition is performed, and the D matrix is returned, along with the corresponding U. Your function must perform row exchanges, if necessary, and the pivots must be well-scaled (to reduce roundoff error) using the technique of partial pivoting. If the function call does not contain the proper number of input or output arguments, or if A is singular or not square (i.e. rectangular), then you must notify the user by throwing a suitable corresponding error message using the MATLAB error function. (Hint: You'll need to set a tolerance to determine when a pivot is zero and when A is singular.)Explanation / Answer
Am not sure may be it was correct.
function [ L,U,D,P ] = LUdecomposition(A)
% Ensures A is n by n
sz = size(A);
if sz(1)~=sz(2)
fprintf('A is not n by n ');
clear x;
return;
end
n = sz(1);
L = eye(n);
U = eye(n);
D = eye(n);
P = A;
for i=1:sz(1)
% Row reducing
if P(i,i)==0
maximum = max(abs(P(i:end,1)));
for k=1:n
if maximum == abs(P(k,i))
temp = P(1,:);
P(1,:) = P(k,:);
P(k,:) = temp;
temp = L(:,1);
L(1,:) = L(k,:);
L(k,:) = temp;
end
end
end
if P(i,i)~=1
temp = eye(n);
temp(i,i)=P(i,i);
U = U * temp;
P(i,:) = P(i,:)/P(i,i); %Ensures the pivots are 1.
end
if i~=sz(1)
for j=i+1:length(U)
temp = eye(n);
temp(j,i) = U(j,i);
U = U * temp;
P(j,:) = P(j,:)-P(j,i)*P(i,:);
end
end
end
P = P';
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.