Reputation: 127
I want to know If it's possible and how, to hide some parts of a line or whole lines of code from a script in MATLAB. For example:
if a=b
x=y+1; x=x^2;
end
And have the x=x^2 hidden, but still run the process. I mean:
if a=b
x=y+1;
end
Upvotes: 0
Views: 3325
Reputation: 125854
(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. ;)
Upvotes: 6
Reputation: 18177
if a==b
x = y+1;
for ind = 1
x = x^2;
end
end
Bit of a wacky way, but you can collapse loop/end
blocks like for
and while
loops. Simply click the -
sign in the editor:
So for two or less lines this doesn't help you, but if you want to hide e.g. 40 lines, it shortens it appreciably.
Another option is to simply chuck in a hundred or so spaces and make it obfuscated:
if a==b
x = y+1; x = x^2;
end
Thanks to excaza the most obfuscated way of all to write x=x^2;
:
eval(cast((sscanf('240,122,240,188,100,118', '%d,')./2)', 'like', ''))
Upvotes: 5