How to obtain a warning message?

6 vues (au cours des 30 derniers jours)
Zoltán Csáti
Zoltán Csáti le 27 Août 2013
I would like to extract the warning message, that a function throws. For example
syms x
solve(sin(1/sqrt(x)))
generates the warning:
Warning: The solutions are parametrized by the symbols:
k = Z_
I want to put the message to a variable programmatically. How can I make this? Thanks.
P.s. I know about lastwarn but I need to handle several warnings not just the last one.

Réponse acceptée

Jan
Jan le 27 Août 2013
Modifié(e) : Jan le 27 Août 2013
As you found out already, lastwarn contains the last message only. You could overload the function warning to create a history of messages:
function varargout = warning(varargin)
persistent MsgList
if isa(MsgList, 'double')
MsgList = {};
end
if nargin == 2 && isempty(varargin{1}) && isa(varargin{1}, 'double')
switch varargin{2}
case 'GetList'
varargout{1} = MsgList;
return;
case 'ResetList'
MsgList = {};
return;
end % No OTHERWISE!
varargout = cell(1, nargout);
[varargout{:}] = builtin('warning', varargin{:});
MsgList{length(MsgList) + 1} = lastwarn;
This adds new messages for commands like warning('off', 'backtrace') also, so much more details are required for a smart behavior. But this demonstrates the general idea.
[EDITED] I've replaced the method to obtain and clear the list of messages. Using a magic string method in the first input is not 100% clean. Now this is used for controlling:
warning([], 'GetList')
warning([], 'ClearList')
Although it is very unlikely that somebody uses the warning message '$GetList', it might be a trap
  3 commentaires
Jan
Jan le 27 Août 2013
The leading '$' should reduce the danger for a collision with a warning message. It is more unlikely that a warning message is called '$GetList' than 'GetList'. But such "magic strings", which cause a different behavios of the function, are a bad idea. I replace this by another approach.
Zoltán Csáti
Zoltán Csáti le 27 Août 2013
Thank you.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Error Handling dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by