MATLAB: Using “If Warning” as a conditional statement

"if warning" returnMATLAB

Hi!
Short Question: I would like my code to perform in a certain way if a warning is issued, no matter the warning. Something like
dbstop if warning
however I do not want it to stop but to break the loop or do other things. Is there a function which I can use in an "if" statement? The only possibility I found was the try – catch blcok but as far as I got, that requires to know your error.
Details/Long Q.: I have a function that takes input and does matrix inversion on many matrices. Sometimes the input is bad (it is randomly generated) and the determinant is say 0, NaN, -Inf, etc. Matlab gives me a warning for that and I want it, as soon as it sees its own warning, to stop executing the funciton and return, so that it can draw again. I used conditional statements at first (if isnan(det(A)) return; end for example), but I have many matrices and the combinations are too many to do it manually. What would be a nice way to do it?

Best Answer

Hi,
you can use lastwarn to get the last warning:
[warnmsg, msgid] = lastwarn
And than you can compare the msgid from the last warning with the msgid from the warning which you get for a bad matrix.
>> inv([eps eps; eps eps])
Warning: Matrix is singular to working precision.
ans =
Inf Inf
Inf Inf
>> [warnmsg, msgid] = lastwarn
warnmsg =
Matrix is singular to working precision.
msgid =
MATLAB:singularMatrix
So you do something like this in your code:
inv(input_from_user)
[warnmsg, msgid] = lastwarn
if strcmp(msgid,'MATLAB:singularMatrix')
//warning was thrown, do something
end