필터 지우기
필터 지우기

How do I return something only if all steps of an conditional statement is true?

조회 수: 2 (최근 30일)
I am attempting to generate a random 4x4 matrix and if all the real parts of the eigenvalues are negative, then compute the inverse matrix of the original random matrix.
m=4;
G=randn(m);
H=eig(G);
J=real(H);
[rowsJ,colsJ]=size(J);
for r=1:rowsJ
if J(r,1)<1
K=G^-1
else
printf("Unable to Compute")
end
end
  댓글 수: 4
Walter Roberson
Walter Roberson 2019년 9월 12일
You should be testing J<0 rather than J<1 if you want negative.
John D'Errico
John D'Errico 2019년 9월 12일
Oh, then the test is just
all(real(eig) < 0)

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2019년 9월 12일
if all(J(:)<1)
K=inv(G);
else
K = [];
printf("Unable to Compute")
end
However... you should rarely be computing the inverse of a matrix. In most cases you should be using other approaches than inv(), such as using the \ operator.
  댓글 수: 4
Stephen23
Stephen23 2019년 9월 13일
편집: Stephen23 2019년 9월 13일
"but why should I not be computing the inverse of a matrix?"
inv is slower and less accurate than the recommended methods of solving systems of linear equations.
The inv documentation explains: "It is seldom necessary to form the explicit inverse of a matrix. A frequent misuse of inv arises when solving the system of linear equations Ax = b. One way to solve the equation is with x = inv(A)*b. A better way, from the standpoint of both execution time and numerical accuracy, is to use the matrix backslash operator x = A\b."

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by