I am running some data processing work in MATLAB and solver uses BACKSLASH operator. Sometimes, I get warning like this:
Warning: Rank deficient, rank = 1390, tol = 1.335195e-010.
Warning: Rank deficient, rank = 1386, tol = 1.333217e-010.
I would like to catch those warnings.
I am trying to convert warning to error and then catch it as described here under title “Trapping warnings”:
http://undocumentedmatlab.com/blog/trapping-warnings-efficiently
In the example, following string has been used to convert warning to error:
s = warning('error', 'MATLAB:DELETE:Permission');
However, I am not sure what string to use for my case. I tried using
s = warning('error', 'Warning: Rank deficient’);
But, it did not work.
Any help would be appreciated.
Regards,
DK
You need to specify the warning identifier, not the warning text. You can find the identifier using the two-output form of lastwarn:
[msgstr, msgid] = lastwarn
In your case, I think the identifier you want is 'MATLAB:rankDeficientMatrix'.
You could try to use lastwarn as an alternative. After your division, call it and compare it with strcmp to the usual warning message, and if its the one you wnat you could manually throw the error you want with error.
As you suggested: you can reset lastwarn throwing an empty warning warning('')
Related
I am trying to handle exceptions gracefully such that when a user enters a character, when a number is expected, he is notified with a custom warning/message.
I know that the try, catch has the following syntax:
try
statements
catch exception
statements
end
I have been trying something like this, to no avail:
number = input('Enter number');
try
assert(isnumeric(number));
catch ME
warning('NOT A NUMBER');
end
I do not understand why the above code fails since assert if it is false, displays the error message 'Assertion Failed'.
I know that using try and catch is a bit of a sledgehammer approach, but I would like to understand how to implement the above functionality. Any tips would be appreciated.
From the help command:
input Prompt for user input.
RESULT = input(PROMPT) displays the PROMPT string on the screen, waits
for input from the keyboard, evaluates any expressions in the input,
and returns the value in RESULT. To evaluate expressions, input accesses
variables in the current workspace. If you press the return key without
entering anything, input returns an empty matrix.
Therefore if a user types in "goat" MATLAB will try to evaluate the variable named "goat". That is not helpful for this problem.
However looking further down the help command:
STR = input(PROMPT,'s') returns the entered text as a MATLAB string,
without evaluating expressions.
This is what is more applicable to your problem.
number = input('Enter number', 's');
try
assert(~isnan(str2double(number)));
catch ME
warning('NOT A NUMBER');
end
Matlab is removing narchk function in future releases and I am trying to change some code to use narginck instead. Now with nargchk, the output was a string and I could pass it to an if statement to display my own error message. Something like
if ~isempty(nargchk(min, max, nargin))
error('custom error message')
end
narginchk automatically gives an error not a string, so I was wondering if there is a way to give a custom error message with narginchk
You cannot supply a custom error message to nargchk and related functions.
There is no need to use nargchk in your case since you don't need default values or anything, just simply check the value of nargin.
if nargin > max || nargin < min
error('custom error message');
end
Alternately, you could use assert to eliminate the if statement.
assert(nargin <= max && nargin >= min, 'Custom Error Message');
If you really want to use one of those functions, you could wrap it inside of a try/catch statement and provide a custom error message
try
narginchk(min, max, nargin)
catch ME
throw(MException(ME.identifier, 'my custom message'))
end
I've got the error of "Error using histc. First Input must be a real non-sparse numeric array" from the following codes.
N=10^4;
d=rand(1,N)>0.5;
symbols=unique(d);
probs = histc(d,symbols)./numel(d);
P/s: I try to generate using randsrc before. It did worked.But, I'm hoping not to use randsrc because it will affect my code later on. Any ideas on this would be appreciated.
Thanks.
Here is the working code
N=10^4;
d=double(rand(1,N)>0.5);
symbols=unique(d);
probs = histc(d,symbols)./numel(d);
I am reading multiple netcdf files using the ncread function in matlab.
For a reason unknown to me, some files (described by FILEPATH in the following) are not properly read and ncread crashes, producing the error message:
Error using internal.matlab.imagesci.nc/openToRead (line 1259)
Could not open FILEPATH for reading.
Error in internal.matlab.imagesci.nc (line 121) this.openToRead();
Error in ncread (line 53)
ncObj = internal.matlab.imagesci.nc(ncFile);
Error in MY_FUNCTION (line 102)
Lon = nanmean(ncread(FILEPATH,'Lon'));
If you know of a method to test netcdf files without crashing, or if you understand what produces this error, any insight would be appreciated.
The standard way is to wrap the possibly-failing statement in a try/catch statement to intercept the thrown exception before interrupting the function execution, like this:
function [out1, out2, ...] = MY_FUNCTION(arg1, arg2, ...)
%//Initial code
try
Lon_data = ncread(FILEPATH,'Lon');
catch ME
warning('MY_FUNCTION:ncread', 'Could not load because <<%s>>',ME.message);
%//Do something to recover from error
%//Return from function if recover not possible
end;
Lon = nanmean(Lon_data);
%//Rest of the code
end
Please note that ... in the function signature above is not valid MATLAB syntax, but rather something that says "here are some inputs and outputs that I don't know how they are declared"; please substitute with your proper in/out declaration.
I have a case where I want to throw an out of range exception in matlab, but also give the reason to why the vector goes out of range (bad backward compatibility). It is of course possible to have some kind of fprintf()... error('out of range'). However, it feels like it may be good to go the proper way here, as
try
a = b(c);
catch err
throw(err,'Identifier');
error('lack support for particular case');
end
The question is: How to create err?; And also: What is the identifier for "out of range" called in matlab?
The reason that the error message is different is because for the fprintf case the out of range should not be passed with only a comment.
In the statement
try
doSomethingThatMayResultInError();
catch me
doSomethingWithTheError(me);
end
me is an object of class MException that contains all information, including stack trace, of the error.
If you would like to add additional information to the error you're throwing, you can do it the following way:
try
doSomethingThatMayResultInError(a,b);
catch me
%# throw a more easy-to-understand error
error(['This use case, i.e. with length of a (%i) different from length of b (%i)'...
'is not supported. Error details: %s'], length(a), length(b), me.message)
end
Of course, you can make error handling more involved by adding e.g. switch/case statements with error identifiers (me.identifier), although you should be advised that error identifiers have been changing a few times in the last few versions of Matlab.
I'm not sure what you mean by 'how to create me?', that gets created for you when the error is thrown. As for checking the identifier, why not just throw the error yourself and inspect the me object (although I think me is a bad name so I'm going to use err instead):
try
a = b(c); %// making sure that the error you want occurs!
catch err
disp(err.identifier);
end