Code stops after first iteration
Show older comments
So I have this MATLAB code for LU decomposition with partial pivoting and the code stops after doing one iteration even though I have added a loop. What could possibly be the reason
function[Q,P]=lupivot(A)
%%LU factorization with partial pivoting%%
[i,j]=size(A);
n=length(A);
if i~=j
disp('The Matrix must be square to proceed further');
end
P=eye(n); %set permutation matrix to I%
Q=zeros(n);%set Q matrix%
for j=1
Q(:,1)=A(:,1);%initialize the first column to first column of A
[temp,pos] = max(abs(Q(1:n,1)));%Finding the maximum value in the column%
if Q(1,1)==temp %Checking if the diagonal element has maximum value%
for k=2:n
Q(1,k)= 1/Q(1,1)*((A(1,k)));
end
else
Rowswap = pos;
Q([Rowswap, 1],:) = Q([1, Rowswap],:);
A([Rowswap, 1],:) = A([1, Rowswap],:);%Swapping the corresponding rows of Q,P and updating A
P([Rowswap, 1],:) = P([1, Rowswap],:);
for k=2:n
Q(1,k)= 1/Q(1,1)*((A(1,k)));
for k=2:n
Q(k,2)= A(k,2)-((Q(k,1)*Q(1,2)));
end
end
end
end
for j=2:n
[temp1,pos1] = max(abs(Q(j:n,j)));%Finding the maximum value in the column%
if Q(j,j)==temp1 %Checking if the diagonal element has maximum value%
for k=j+1:n
Q(j,k)= 1/Q(j,j)*((A(j,k))-(Q(j,1:j-1)*Q(1:j-1,k)));
for k=j:n
Q(k,j)= A(k,j)-(Q(k,1:j-1)*Q(1:j-1,j));
end
end
else
rowswap = j-1+pos1;
Q([rowswap, j],:) = Q([j, rowswap],:);
A([rowswap, j],:) = A([j, rowswap],:);%Swapping the corresponding rows of Q,P and updating A
P([rowswap, j],:) = P([j, rowswap],:);
for k=j+1:n
Q(j,k)= 1/Q(j,j)*((A(j,k))-(Q(j,1:j-1)*Q(1:j-1,k)));
for k=j:n
Q(k,j)= A(k,j)-(Q(k,1:j-1)*Q(1:j-1,j));
end
end
j=j+1;
end
end
end
OUTPUT
>> [Q,P]=lupivot(A)
Q =
12.0000 -0.6667 0.3333 0.8333
3.0000 -11.0000 -0.1818 -0.0455
6.0000 2.0000 0.3636 -Inf
-6.0000 0 4.0000 0
8 Comments
Is this the loop you have added?
for j=1
Anyway, you should indicate where you have added something and what your expected output is.
Asha Shibu
on 3 Sep 2018
dpb
on 3 Sep 2018
You've got double-nested loops on the same index in
...
for k=j+1:n
Q(j,k)= 1/Q(j,j)*((A(j,k))-(Q(j,1:j-1)*Q(1:j-1,k)));
for k=j:n
Q(k,j)= A(k,j)-(Q(k,1:j-1)*Q(1:j-1,j));
end
end
...
I've not tried to read the code see if could decipher what might possibly be intended here, but this can't be correct...
Asha Shibu
on 3 Sep 2018
Asha Shibu
on 3 Sep 2018
Kevin Chng
on 4 Sep 2018
Edited: Kevin Chng
on 4 Sep 2018
Hi,
According to dpb, double nested on same index
for k=1:1:n
for k=1:1:n
end
end
%Try change the inner loop index k to other name (j):
for k=1:1:n
for j=1:1:n
end
end
Asha Shibu
on 4 Sep 2018
It is recommended to avoid i and j as loop indices, as these are used for the imaginary unit:
It is much clearer and less buggy to use ii and jj:
for ii = 1:n
...
for jj = 1:n
...
end
end
Answers (0)
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!