(wringing hands with evil grin on face)
If you really want to mess with people like this, you're going to want to go down the operator overloading route. Come with me on a journey where you will almost certainly shoot yourself in the foot while trying to play a joke on someone else!
(lightning crackles over the laughter of a madman)
I've discussed this in a few other questions before (here and here). Basically, you can change the default behavior of built-in operators for MATLAB data types. In this case, we'll change how the plus
operator works for variables of class double
(the default variable type). Make a folder called @double
on your MATLAB path, then create a file called plus.m
and put the following code inside it:
function C = plus(A, B)
C = builtin('plus', A, B);
if strcmp(inputname(1), 'y')
C = C.^2;
end
end
Now, try it for yourself...
>> y=1; % Initialize y
>> x=y+1
x =
4 % Wait a minute...
>> x=1+1
x =
2 % OK
>> x=1+y
x =
2 % OK
>> x=y+1
x =
4 % What?!
>> x=y+2;
x =
9 % No!!
>> y=3;
>> x=y+1
x =
16 % Oh noes! I've been hax0red!!11!1!
How it works:
The new plus
function shadows the built-in one, so it gets called when performing addition on doubles. It first invokes the built-in plus
to do the actual addition using the builtin
function. This is necessary, because if you wrote C=A+B;
here it would call the phony plus
again and cause infinite recursion. Then, it uses the inputname
function to check what the variable name of the first input to the function is. If it's 'y'
, we square the result before returning it.
Have fun!!!
...and remember to remove it when you're done. ;)