This is a rhetorical question about the uplus
function in MATLAB, or its corresponding operator, the unary plus +
.
Is there a case where this operator is useful? Even better, is there a case where this operator is necessary?
This is a rhetorical question about the uplus
function in MATLAB, or its corresponding operator, the unary plus +
.
Is there a case where this operator is useful? Even better, is there a case where this operator is necessary?
It is not necessary, a language without a unary plus does not allow to write +1
. Obviously you could also write 1
but when importing data which always writes the +
or -
it's very nice to have.
Searching some source codes, I found a curious use of +
A=+A
which replaced the code:
if ~isnumeric(A)
A=double(A);
end
It casts chars and logicals to double, but all numeric data types remain untouched.
It can be useful when defining new numeric types.
Suppose you define quaternion and overload uplus
:
classdef quaternion
...
end
Then in your code you can write:
x = quaternion(...);
y = [+x, -x];
z = +quaternion.Inf;
t = -quaternion.Inf;
If you don't you cannot have same syntax as for other numeric.
PS: To the question "is it useful" (in the sence mandatory for some syntaxes) ... well I can't find any reason ... but sometimes writting '+x' make things clearer when reading back the code.
I'm not sure if this fully constitutes "useful" or if it's the best programming practice, but in some cases, one may wish to use the unary +
for symmetry/clarity reasons. There's probably a better example, but I'm thinking of something like this:
A = [+1 -1 +1;
-1 +1 -1;
+1 -1 +1];
As for the uplus
function, it's kind of a NOOP for numeric operations. If one writes a function that requires a function handle input to specify an operation to perform, it might be useful to have do nothing option.
Lastly, numeric operators can be overloaded for other classes. The uplus
function could have more use in other built-in classes or even one you might want write yourself.