When can I use ! and ~?

How and where can I use ! and ~?
When and where can I use [~,IDX_OF_MAX] =max(x)?
When and where can I use [!, IDX_OF_MAX] =max(x)?

1 Like

For negation you can use both operators. The tilde is used for Matlab compatibility so use that if you have code that needs to run on both programs. Octave’s scripted functions use the exclamation but user code can use either.

For ignoring return values I thought it was only the tilde operator but today I learned that the exclamation works there too! Both Octave’s own scripted functions and all of Matlab use the tilde for that case, so use that if you don’t have a preference.

@jwe: was it intended for the exclamation to also be used as the ignore-return-value operator?

1 Like

I don’t think so. It’s allowed because the parser uses

magic_tilde     : EXPR_NOT
                  {
                    OCTAVE_YYUSE ($1);

                    $$ = parser.make_black_hole ();
                  }
                ;

and the lexer recognizes either ~ or ! as EXPR_NOT. Maybe we should fix that so only ~ is allowed as the symbol for ignoring outputs?

1 Like

That seems reasonable to me.

I would also recommend only letting ~ serve that purpose.

This was new info to me but matlab documents that ~ also works for explicitly ignoring inputs in function definitions. I personally can’t think of a use case, which is probably why i didn’t know about it. the matlab example is a case where something else ‘forces’ you to have a certain number of function inputs, like callback functions, even though you don’t need that many. Ignore Inputs in Function Definitions - MATLAB & Simulink

Octave appears to support the same:

function [a,b,c] = myfun(A,~,C)
  a = exist("A","var");
  b = exist("B","var");
  c = exist("C","var");
end
>> [a,b,c] = myfun(1,2,3)
a = 1
b = 0
c = 1

and it appears to support both ! and ~ there as well.

function [a,b,c] = myfun(A,!,C)
  a = exist("A","var");
  b = exist("B","var");
  c = exist("C","var");
end
>> [a,b,c] = myfun(1,2,3)
a = 1
b = 0
c = 1

also recommend that be limited to ~.

Yes, the code that handles that is common to both input and output lists, so one fix will do both.

I pushed the following change:

http://hg.savannah.gnu.org/hgweb/octave/rev/ef9c804676b9

2 Likes

You can find an example of such use case in Octave’s graphics callback function. Since those functions are called by the interpreter with two arguments (a graphics handle and an event structure), we need to allow the arguments to be passed, even though we don’t need them. Otherwise Octave would throw an an error “two many inputs”. Here is an example of such function:

callback = @(~,~) disp ("Figure clicked!");
set (gcf, "buttondownfcn", callback);
2 Likes