14 September, 2013

Using the ans variable

  • What is the ans variable?
  • How to use the ans variable to reduce the size of a MATLAB Cody solution?

Variable ans is created automatically in MATLAB when no output argument is specified:

>> y = 42
y =
42
>> 42 ans =
42

In the first case we have defined that variable y shall get the numeric value. In the second case the output argument is not given, so ans will equal to 42.

This approach can be used for function output arguments too:

function out = twice(x)
    out = x * 2;
end

The example above does the same as:

function ans = twice(x)
    x * 2;
end

How to use this in MATLAB Cody Challenge to reduce code size

In MATLAB Cody the sent solutions are ordered by their size, which can be reduced: the code complexity decreases by not defining the output argument but using the ans variable. For example have a look at Problem 1046. Add two numbers, where the evident solution has a code size of 12:

function y = addup(x)
    y = sum(x);
end

By using the ans variable the code size decreases to 10:

function ans = addup(x)
    sum(x);
end

This a simple and valid trick to reduce the code size. Of course in case of real-life programming solutions, using this is not recommended to avoid some headache in the future...

Tags:anscody
         

New comment

comments powered by Disqus