Matlab: How can i stop a the whole function in matlab? - matlab

I have a function in matlab calculating something. Within that function I open another function to calculate something for it.
Now in this second function I have some case where I just want to stop everything if some certain condition is true (so I want to end both functions)
I don't want an error message or anything; Is there a command for that?
If I just type in error I get some notice in red with a message such as:
error: Invalid call to error. Correct usage is:
-- Built-in Function: error (TEMPLATE, ...)
-- Built-in Function: error (ID, TEMPLATE, ...)
error: called from:
error: /usr/share/octave/3.8.1/m/help/print_usage.m at line 89, column 5
>>>error: /home/john/wpq.m at line 75, column 4
error: /home/john/test.m at line 23, column 21
if I write error('blabla') I still get:
>>>error: blabla
error: called from:
error: /home/john/wpq.m at line 75, column 4
error: /home/john/test.m at line 23, column 21
I would like to get no output because I can write one line above already something like disp('the test on this number failed').

You could try placing a try/catch block in your main function to expect the condition under which you want code execution to stop.
I don't believe that there is any one command that allows code to stop execution from a function within a function.

There are a number of ways of doing what you want. Typically error is only meant to be used for things that actually is errors. You do for example get an "index out of bounds" error if you try to access an element outside the array. In case what happens is an error you should send an error message to inform users about what happens and highlight that this is an error. However, in case you only want this particular calculation to end and not the program I would instead recommend try-catch and printing the error message in catch.
In case this is normal termination (or if only a particular function terminates unnormally and this is expected for some input) you can either use a termination condition (function [out,success] = myFun(in)) or try-catch. Both are accepted, though I use to prefer the termination condition approach for normal termination and try-catch for unnormal termination (of functions). Unnormal termination can for example be when a function have to be terminated before all output variables are calculated. I use to prefer to have an exception thrown instead of a function returning invalid values (but a c-programmer would probably argue differently).
For the record, there is a return-statement in Matlab which terminates a particular function.
It is hard to recommend a particular approach without knowing the situation you are in, but this text would give you some different options to be choose between. Know that error handling seldom have standard approaches which can be said to be "right". It is often up to the programmer to decide what is suitable and that is typically a part of the design.
Good luck!

Related

return statement after throw error in matlab

For my simple code It seems that the return statement is not needed after the error statement.
Does that mean the function would be early terminated once error is thrown?
If the above is true, what if i do want to process with the rest of function even after an error is thrown. For example, i can still compute c = a - b in my function.
Yes, the error terminates the program.
As suggested by Hoki, use a warning instead.
Note: Your function will throw anyway, if only modifying the code to use warning. This is because the return variable c is not assigned before after the if-statement.

Exception/Error Handling in q kdb -- Alternative of Try-Catch-Finally(Java)/Try-Except-Finally(Python)

As we have try-catch in java, I can find trap-at in q kdb.
But my requirement is of try-catch-finally i.e in try block I'm opening odbc connection and in finally I want to close odbc connection.
Sudo code:
try{
con=openODBCConnection(dbName);
//n statements;
}catch(Exception e){
catchingNotSoImpException(e)
}finally{
closeODBCCon(con);
}
This is a fairly generic approach to using try-catch-finally logic in kdb, which separates out the try-catch, always runs the "finally" function. This returns the output if successful in either the try or the catch if necessary, or the error code if both try and catch have broken, allowing (potentially) more useful investigation and/or security on breaks:
tcf:{[t;c;f]
r:#[(1b;)value#;t;#[(1b;)c#;;(0b;)::]];
f[];
$[r 0;r 1;'`$r 1]}
The top line is the "try-catch" portion.
#[(1b;)value#;t;#[(1b;)c#;;(0b;)::]]
The function is called like so:
tcf[(tryfunc;1;`a);catchfunc;finallyfunc]
so the input has to be something that can be value'd in kdb - symbol, function and argument list, or string.
This can be used as-is, but for an explanation:
The key portion of logic here are the projections of (1b;) and (0b;) together with # on the value or c functions tell that operation to wait on input - so within the first part:
(1b;)value#
waits for the input t - if the value operation succeeds, (1b;correctOutput) is returned, i.e. the projection is executed.
If that fails, the error is passed to
#[(1b;)c#;;(0b;)::]
Which is basically the same thing, but instead of value, it uses the catch function, c. This is a projection which takes the input passed from the failed value before, then applies the same operations as above. Failed output is passed to a global null ::.
This ensures the data structure r has a leading 1b if either the try or catch was successful, and a 0b if both failed.
The finally function is then run, and the return is either the successful answer or a thrown error in the case of double failure.
Examples using similar definitions to Rahul's answer:
q)tryfunc
{x+y}
q)workingcatchfunc
{show "catch";100}
q)brokencatchfunc
{show "catch";1+`a}
q)finallyfunc
{show"finally"}
q)tcf[(tryfunc;1;1);workingcatchfunc;finallyfunc]
"finally"
2
q)tcf[(tryfunc;1;`a);workingcatchfunc;finallyfunc]
"catch"
"finally"
100
q)tcf[(tryfunc;1;`a);brokencatchfunc;finallyfunc]
"catch"
"finally"
'type
This works with functions taking any number of arguments also:
q)tcf[(monot;1);brokencatchfunc;finallyfunc]
"finally"
10
q)tcf[(monot;`);brokencatchfunc;finallyfunc]
"catch"
"finally"
'type
There is no finally block in KDB. One approach to get functionality closer to this in KDB is to write a function for final block and call it in both try and catch. This will not guarantee that this function will be executed always but will cover most of the cases.
q)finally:{show "finally"}
q)try:{show "try"; show x+y;finally[]}
q)catch:{show "catch"; finally[]}
q).[try;1 2;catch]
Output:
"try"
3
"finally"
Now, it is important where you call the finally function inside try and catch. The order of call could change the behavior. My suggestion is to call it at the last and always return result from finally function. If there is any return value from try or catch functions then pass that value to finally function. This will reduce the chances of errors, make code simple and also remove other overheads like call ordering issue.
Example of a return value from try block:
q) finally:{show "finally"; :x}
q) try:{show "try";r:x+y;finally r}
q) catch:{show "catch"; finally[]}
q) .[tyr;1 2;catch]
Output
"try"
"finally"
3

How can I 'unparse' a parse tree in q/kdb+?

I am trying to create an automatic 'debugger' for tracing function flow. Because I'm not a god, I do make mistakes, and when I do, I normally end up throwing a bunch of "show" in my functions. What I'm looking to do is create a function that will insert shows prior to each line for each variable used in an expression on that line and any variable assigned to in the previous.
Imagine I have a function f that is throwing an unhelpful error. I would insert
f: debugwrap[f];
after the function definition to insert the appropriate debugging within the lines of function string, parse, and return the augmented function.
I have had success handling the params and simple functions, but where I have trouble is where semicolons do not indicate eol, such as in function calls. Using parse on the function body, I can easily break out all the lines and find the required variables, but once I do that, I need to 'unparse' each line in the function. That unparsing is giving me trouble, especially where functions are translated to what I believe is k - such as "*:".
Simple example with only initial logging:
q)f: {[a;b] a: a xexp b; c: a-first `int$-1#string first table[`symbols]; :c }
q)df: dp[f;";"]
q)df
"{[a;b] show "a is ",string[a]; show "b is ",string[b]; a : a xexp b;c : a - *:`int$-1#$:*:table`symbols;: c;}"
q)parse df
ERROR: *:
What I'm doing now is recursively walking through the parse tree and reconstructing the call. That is painful and not yet yielding results. What I think is the best way is to get the information I need out of each parse subtree, then unparse that subtree and append it to my function string.
Appreciate any help you all can offer.
The best place to see how debugging might be done, is with this code: http://code.kx.com/q/ref/debug/

GtkAda simple chat error

I'm writing simple chat program in Ada, and I'm having problem with chat window simulation - on button clicked it reads text form entry and puts it on text_view. Here is the code I've written and here is the compile output:
gnatmake client `gtkada-config`
gcc -c -I/usr/include/gtkada client_pkg.adb
client_pkg.adb:14:19: no candidate interpretations match the actuals:
client_pkg.adb:14:37: expected private type "Gtk_Text_Iter" defined at gtk-text_iter.ads:48
client_pkg.adb:14:37: found type "Gtk_Text_View" defined at gtk-text_view.ads:58
client_pkg.adb:14:37: ==> in call to "Get_Buffer" at gtk-text_buffer.ads:568
client_pkg.adb:14:37: ==> in call to "Get_Buffer" at gtk-text_buffer.ads:407
client_pkg.adb:15:34: no candidate interpretations match the actuals:
client_pkg.adb:15:34: missing argument for parameter "Start" in call to "Get_Text" declared at gtk-text_buffer.ads:283
client_pkg.adb:15:34: missing argument for parameter "Start" in call to "Get_Text" declared at gtk-text_buffer.ads:270
gnatmake: "client_pkg.adb" compilation error
Can anyone tell me what is the problem, since I have no idea why procedure Get_Buffer expects Gtk_Text_Iter, and why Get_Text miss Start parameter?
You have to call the correct procedures/functions.
In your example, you call Gtk.Text_Buffer.Get_Buffer, not the correct Gtk.Text_View.Get_Buffer. This is because you with and use Gtk.Text_Buffer, but don't use Gtk.Text_View. You should be careful what you use. Same for Get_Text.
If you add use clauses for Gtk.Text_View and Gtk.GEntry, those errors should disappear.
But I give you an advice: try to use as few as possible use clauses. That way you always know what function is really called.
TLDR: Add use Gtk.Text_View; use Gtk.GEntry; to the declaration part of the On_Btn_Send_Clicked procedure.

ILGenerator, make decision on return value of null

il.Emit(OpCodes.Callvirt, _compactBinaryReader_ReadObject);
this function is called and at a special condition a return value of 'null' is provided.
if that value is null i have to take a decision whether to jump on to a label or not
using after the method call
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Brfalse_S, DECISION);
gives me an exception "JIT Compiler encountered an internal limitation." when i call that function, the code builds correctly though.
tried OpCodes.Brfalse too.
what am i doing wrong ?
Found reasonS to the above problem,
one thing which should be understood that when an exception of
'CLR: Verification for Runtime Code Generation'
is thrown it means the code written is not in the correct format and when it is evaluated by the assembler it does not accept the written code, problem is usually because of stacks having extra values or less.
"JIT Compiler encountered an internal limitation." is thrown when at runtime it was expecting something else we provide something else in value or when stack has something else when something else was required.
In short, the later exception is thrown at runtime and the other is thrown when pre Run conditions are not met.
anyways i found the reason, i had some values still present on stack that i did not pop if Condition was met, so the POP OpCode did the trick, and by the way for me the Dup OpCode never worked out, it always pushes a null value on stack rather than duplicating the top most value.