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
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
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 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!