I am having trouble setting up my For loop ?
1 view (last 30 days)
Show older comments
daniel choudhry
on 2 Oct 2020
Answered: Walter Roberson
on 2 Oct 2020
I am trying to create a Matlab function that computes A inverse for a given NxN invertible matrix. but I am having trouble with my code. Exactly, in the For loop part of it
function my_inverse
rand('seed',1);
A = rand(100,100);
B = zeros(100,100);
[L, U, p]= lu_fac_pp(A);
for j = 1:100
%compute b1,b2...b100 ------> B
c=perm_b(b,p);
d=ultt_sys(L,c);
x=utt_sys(U,d);
B=x;
end
%check for accuracy
I = eye(100);
C =abs(A*B-I);
disp('max_entry & |A*B-I| using my_inverse');
max(max(C))
disp('----------------');
B = inv(A);
C = abs(A*B-I);
disp('max_entry & |A*B-I| using MATLAB');
max(max(C))
disp('------------------');
end
0 Comments
Accepted Answer
Walter Roberson
on 2 Oct 2020
for j = 1:100
%compute b1,b2...b100 ------> B
c=perm_b(b,p);
d=ultt_sys(L,c);
x=utt_sys(U,d);
B=x;
end
In the loop, you assign to c, d, x, B. You do not assign to b or p, so every iteration of the loop, c is going to have the same result. You do not assign to L, so since c is always going to have the same result, then the ultt_sys(L,c) calculation is always going to have the same result, so d will always be the same. Likewise because you also do not assign to U and we have shown that d will always be the same, then we see that x must always have the same result. And since x is always the same, B=x means that B will always have the same result.
Therefore given that code, there is no point in executing the loop 100 times: the output will be exactly the same as if you only executed once. (Unless, that is, one of the functions you call there uses random numbers.)
Note also that every iteration you are overwriting all of B.
Your loop also does not depend upon j at all.
0 Comments
More Answers (0)
See Also
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!