Changing for loop to backslash

3 ビュー (過去 30 日間)
Ruan De Beer
Ruan De Beer 2022 年 9 月 14 日
編集済み: Torsten 2022 年 9 月 14 日
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
Solution of system of equation for M = 10 is
2.0000 2.0000 18.0000 13.6364 2.0000
Solution of system of equation for M = 20 is
4.0000 4.0000 18.2222 14.3434 4.0000
Solution of system of equation for M = 30 is
6.0000 6.0000 18.4444 15.0505 6.0000
Solution of system of equation for M = 40 is
8.0000 8.0000 18.6667 15.7576 8.0000
Solution of system of equation for M = 50 is
10.0000 10.0000 18.8889 16.4646 10.0000
Solution of system of equation for M = 60 is
12.0000 12.0000 19.1111 17.1717 12.0000
Solution of system of equation for M = 70 is
14.0000 14.0000 19.3333 17.8788 14.0000
Solution of system of equation for M = 80 is
16.0000 16.0000 19.5556 18.5859 16.0000
Solution of system of equation for M = 90 is
18.0000 18.0000 19.7778 19.2929 18.0000
Solution of system of equation for M = 100 is
20 20 20 20 20

採用された回答

Torsten
Torsten 2022 年 9 月 14 日
編集済み: Torsten 2022 年 9 月 14 日
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
Elapsed time is 0.341871 seconds.
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
Elapsed time is 0.282530 seconds.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLinear Algebra についてさらに検索

タグ

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by