How to avoid using 'diag' function?

6 ビュー (過去 30 日間)
Mohammadamin Malek Pour
Mohammadamin Malek Pour 2017 年 4 月 25 日
回答済み: Walter Roberson 2017 年 4 月 25 日
Hello all
I've written this code to calculate vector x in Ax=b.
However, it seems that I shouldn't use diag function in my code. How can I do that? Is there any other way to do the same thing without using any Matlab built-in functions?
Thanks
function x1 = axb(A,b,e)
%This function takes the matrix of coefficients A and the vector b and the
%tolerance e as input.The output of the function shows both the number of
%iteration and the solution x.
n = length(b);
for k=1:n %k is the number of iterations
M(k)=b(k)/diag(A(k,k));
end
x0=transpose(M);
for j=1:n
x(j)=((b(j)-A(j,[1:j-1,j+1:n])*x0([1:j-1,j+1:n]))/A(j,j));
end
x1 = x';
k = 1;
while norm(x1-x0,1)>e
for j=1:n
x_new(j)=((b(j)-A(j,[1:j-1,j+1:n])*x1([1:j-1,j+1:n]))/A(j,j));
end
x0=x1;
x1=x_new';
k = k + 1;
end
k;
fprintf('\nIteration: %3d\n',k)
x = x1';

採用された回答

Walter Roberson
Walter Roberson 2017 年 4 月 25 日
You have a simple for loop over variable k, so inside the for loop, k is going to be a scalar. A(k,k) would then be a scalar. diag() applied to a scalar is going to return the same value. You can just skip the diag call,
M(k)=b(k)/A(k,k);
Note: more efficient would be to not use a loop, and instead use
M = b ./ diag(A);
... unless length(b) is not the same as the length of the diagonal of A.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by