MATLAB issue with Exception Handling - matlab

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

Related

Is there a solution to matlab claiming insufficient input arguments when enough are being supplied?

I have a custom function I have made, which requires two input arguments. This is the opening line of the function, clearly showing it needs just two input arugments:
function [file,frame,vertices,edges,faces,faceOrders,edgeOrders] = FOLD_reader(filename,rundocfolder)
The FOLD_reader function is called within another function (FEAfromFOLDVaryingStiffness), using the following line of code:
[~,frame,vertices,~,faces,~,~] = FOLD_reader(filename,rundocfolder);
To which matlab claims:
Not enough input arguments.
Error in FEAfromFOLDVaryingStiffness (line 12)
[~,frame,vertices,~,faces,~,~] = FOLD_reader(filename,rundocfolder);"
However, if I copy and paste the offending line into the command window, it works perfectly. The filename and rundocfolder variables are definitely defined in FEAFromFoldVaryingStiffness which calls FOLD_reader, as they are among the input arguments of the FEAFromFold(etc) function itself.
Has anyone had any experience with this seemingly bizzarre error? To me it makes no sense at all.
If it's a help here are the lines up to the error point inside FEAfromFOLDVaryingStiffness:
function [] = FEAfromFOLDVaryingStiffness(filename,meshsize,displacement,m,n,stiffnessvary,rundocfolder)
%Comments ommitted for brevity
[~,frame,vertices,~,faces,~,~] = FOLD_reader(filename,rundocfolder);
I'm an idiot, I called the FEAfromFOLDVaryingStiffness with one too few arguments, I'd left out m or n or something and so the last input variable (rundocfolder) was undefined, which showed up as an error with fold_reader inside the FEAfromFOLDVaryingStiffness function, instead of where the error actually was: the top level script.

Is there a way way to generate a custom error message using narginchk in matlab?

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

Preventing "MATLAB:unassignedOutputs" in Matlab

I'm looking to both catch and handle the "unassignedOuputs" error in Matlab. More specifically, looking at the following code:
try
[out1,out2]= somefunction(in1,in2);
catch err
if strcmp(err.identifier,'MATLAB:unassignedOutputs')
<some code>
else
rethrow(err);
end
end
If "somefunction" does not assign out2 and the resulting error is caught, is it possible to somehow retrieve the rest of the outputs from the function (in this case out1)? If not, is there a way to re-call the function ignoring that value so the function will not throw the error?
As far as I can tell, there is no way to retrieve variables once the function has been terminated with this error. For the case when the first output is produced but not the second, you could retry it with just one output, naively something like:
try
[out1,out2]= somefunction(in1,in2);
catch err
if strcmp(err.identifier,'MATLAB:unassignedOutputs')
try
out2 = [];
out1 = somefunction(in1, in2);
catch err2
% rethrow original error
rethrow(err)
end
else
rethrow(err);
end
end
To display a message saying which output wasn't assigned, you'd have to parse err.message (although the default message itself should be reasonably clear).
But getting this to work if you have more than two outputs, and you don't know which might have not been properly defined, would not be simple. And if the first output is not defined, this won't work at all. In that case you would have to, I think, edit the function itself.
If the specific use case is checking a bunch of student codes which all take the same inputs and provide the same outputs, an alternative option would be to provide them with a function template which contains a check at the end if the outputs exist, and if not sets them to empty and displays your custom message.

How to get a function from a edit box in matlab

I have created a GUI in matlab with a edit box and the user should enter a function so the program may evaluate some values.
However how do I retrieve the function in the textbox and how do I make the proper validations for example if the user enters "sin(coserewrwfc(x))"
My code is:
f = get(handles.funcion,'String');
f =inline(f)
f(0)
Thanks for your help
Here's one way of going about it. Basically it's the same as your code, but in a try/catch block so that if there is an error trying to do f(0), the code will keep running. It will enter the catch statement, where you can manage the error, maybe by displaying a message box asking for the function to be entered again.
try
f = inline(get(handles.funcion,'String'));
f(0); %// try something that would fail if the function is defined incorrectly
catch
disp('There was a problem, please try again')
end

Throw "out of range" in matlab

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