Changing for loop to backslash
5 views (last 30 days)
Show older comments
How do I change this code to not have a for loop. Hint: one backslash with multiple right-hand sides, solved simultaneously.
% Create a matrix of the coefficients
A = [6 -1 0 0 0; -3 3 0 0 0; 0 -1 9 0 0; 0 -1 -8 11 -2; -3 -1 0 0 4];
% Compute the LU Factorization
[L,U,P] = lu(A);
% Loop for each value of M from 10 to 100 with increments of 10
for M = 10 : 10 : 100
% Create a column vector of right hand side values
b = [M; 0; 160; 0; 0];
% Use the factors from LU factorization to solve
% two triangular linear systems
y = L\(P*b);
c = U\y;
% Print the solution of system of equation for current value of M
fprintf('\nSolution of system of equation for M = %d is\n', M);
disp(c);
end
0 Comments
Accepted Answer
Torsten
on 14 Sep 2022
Edited: Torsten
on 14 Sep 2022
A = [6 -1 0 0 0; -3 3 0 0 0; 0 -1 9 0 0; 0 -1 -8 11 -2; -3 -1 0 0 4];
b = [10:10:100;repmat([0; 160; 0; 0],1,10)];
dA = decomposition(A);
tic
for i=1:100000
c = dA\b;
end
toc
or
A = [6 -1 0 0 0; -3 3 0 0 0; 0 -1 9 0 0; 0 -1 -8 11 -2; -3 -1 0 0 4];
b = [10:10:100;repmat([0; 160; 0; 0],1,10)];
[L,U,P] = lu(A);
tic
for i=1:100000
y = L\(P*b);
c = U\y;
end
toc
0 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!