How to reduce the Cody size of a solution


Having tackled a given problem is not the end of the game, and the fun is far from over. Thanks to the test suite in place, we can continue tweaking our solutions ("refactoring") so that it still passes the tests while improving its ranking with regard to "Cody size".
Although reducing the Cody size does not necessarily mean a solution will perform more efficiently nor be more readable (quite the contrary, actually…), it is a fun way to delve into the intricacies of MATLAB code and maybe win a Cody Leader badge!
I am not talking about just basic hacks. The size constraint urges us to find an “out-of-the box” way of solving a problem, a way of thinking creatively, of finding other means to achieve a desired computation result, that uses less variables, that is less cumbersome, or that is more refined.
The past few days have taught me several useful tricks that I would like to share with anyone wishing to reduce the solution size of their Cody submission. Happy to learn about other tricks you may know of, please share!
  1. Use this File Exchange submission to get the size of your solution: https://fr.mathworks.com/matlabcentral/fileexchange/34754-calculate-size
  2. Use existing MATLAB functions that may already perform the desired calculations but that you might have overlooked (as I did with histcount and digraph).
  3. Use vectorization amply. It’s what make the MATLAB language so concise and elegant!
  4. Before creating a matrix of replicated values, check if your operation requires it. See Compatible Array Sizes for Basic Operations. For example, you can write x == y with x being a column vector and y a row vector, thereby obtaining a 2 by 2-matrix.
  5. Try writing out for loops instead of vectorization. Sometimes it’s actually smaller from a Cody point of view.
  6. Avoid nested functions and subfunctions. Try anonymous functions if used in several places. (By all means, DO write nested functions and subfunctions in real life!)
  7. Avoid variable assignments. If you declare variables, look for ones you can use in multiples places for multiple purposes. If you have a variable used only in one place, replace it with its expression where you need it. (Do not do this in real life!)
  8. Instead of variable assignments, write hardcoded constants. (Do not do this in real life!)
  9. Instead of indexed assignments, look for a way to use multiplying or exponentiating with logical indexes. (For example, compare Solution 14896297 and Solution 14897502 for Problem 61069. Clueless - Lord Ned in the Game Room with the Technical Computing Language).
  10. Replace x == 0 with ~x if x is a numeric scalar or vector or matrix that doesn’t contain any NaN (the latter is smaller in size by 1)
  11. Instead of x == -1, see if x < 0 works (smaller in size by 1).
  12. Instead of [1 2], write 1:2 (smaller in size by 1).
  13. sum(sum(x))” is actually smaller than “sum(x, 1:2)
  14. Instead of initialising a matrix of 2s with 2 * ones(m,n), write repmat(2,m,n) (smaller in size by 1).
  15. If you have a matrix x and wish to initialize a matrix of 1s, instead of ones(size(x)), write x .^ 0 (works as long as x doesn’t contain any NaN) (smaller in size by 2).
  16. Unfortunately, x ^-Inf doesn’t provide any reduction compared to zeros(size(x)), and it doesn’t work when x contains 0 or 1.
  17. Beware of Operator Precedence and avoid unnecessary parenthesis (special thanks to @Stefan Abendroth for bringing that to my attention ;)) :
  • Instead of x * (y .^ 2), write x * y .^2 (smaller in size by 1).
  • Instead of x > (y == z), write y == z < x (smaller in size by 1).
18. Ask help from other solvers: ideas coming from a new pair of eyes can bring unexpected improvements!
That’s all I can see for now.
Having applied all those tips made me realise that a concise yet powerful code, devoid of the superfluous, also has a beauty of its own kind that we can appreciate.
Yet we do not arrive at those minimalist solutions directly, but through several iterations, thanks to the presence of tests that allow us to not worry about breaking anything, and therefore try out sometimes audacious ideas.
That's why I think the main interest lies in that it prompts to think of our solutions differently, thereby opening ways to better understand the problem statement at hand and the inner workings of the possible solutions.
Hope you’ll find it fun and useful!
P.S.: Solvers, please come help us reduce even more the size of the leading solution for Problem 61069. Clueless - Lord Ned in the Game Room with the Technical Computing Language!
Stefan Abendroth
Stefan Abendroth on 11 Dec 2025
Well deserved award for the post of the week, @WANG Zi-Xiang!
Looking around the vast space of Cody problems, we can actually see brilliant patterns that improve both Cody size and code qualities (such as readability, maintainability, performance, memory consumption), and some nasty hacks that are just specific to that particular way of measuring code size in MATLAB:
Some problem providers included additional test cases to ban these kind of hacks from their solution space. Nevertheless, I think we used these tricks responsibly - and hacking is fun!
WANG Zi-Xiang
WANG Zi-Xiang on 7 Dec 2025
new updates ;)
20. If you know the n the number of elements of an array x, don't write x(end), use x(n).
21. Use the function deal to handle multiple variable assignments.
22. Remove redundant or unnecessary calculations.
23. Add in redundant calculations, sometimes it simplifies the arrangement of the instructions (e.g., it can help factorize for loops).
24. Try changing the order of the instructions or grouping them differently to see new patterns.
25. Shift the dimensions of your arrays to see if you can exploit the implicit application of vectorized functions along the first dimension, so that for example, instead of sum(X, dim) you'll only need to write sum(X), and instead of max(X, [], dim), you'll only need max(X).
26. Use exception handling instead of conditionals (avoid this in real life!)
27. Convert chars into integers: '1' - 48 gives 1
28. Convert integers into chars: char(p + 'a')
29. Use str2num to produce arrays with hardcoded sizes or values: str2num('0 1 2'), str2num('reshape(1:4,2,2)'), str2num('repmat(1:3,2,5)'), str2num('eye(3,4)'), str2num('ones(2,3,4)').
30. If you have a new idea, before submitting your new solution, examine again all the other tricks listed here.
WANG Zi-Xiang
WANG Zi-Xiang on 2 Dec 2025 (Edited on 2 Dec 2025)
We can now add to this list, thanks to @Vasilis Bellos' suggestion:
19. If c is a cellarray containing numeric vectors, instead of [c{:}], use cell2mat(c) (smaller by 2).
Vasilis Bellos
Vasilis Bellos on 2 Dec 2025
Funny thing is, I actually discovered cell2mat through Cody. Before this I didn't know it existed, and I had unnecessarily written my own cellcat function, which I often used for inlining things like arrayfun w/ 'UniformOutput' = false.
In some Cody problems, you can often shorten the solution of a question with multiple input arguments if you pass them as variable arguments using varargin, and then expand them into a comma-separated list and concatenate them like you showed. I was able to figure out that bit, but I didn't know about cell2mat until after I saw that the top ranking solution which used that instead was a couple of characters shorter. I guess this is another example of how Cody can help with good programming practices if you look at the solutions of other experienced coders. As others have mentioned, it's not always a hack, as there's sophistication and elegance in many of the top ranking solutions.
Stefan Abendroth
Stefan Abendroth on 3 Dec 2025
That one comes in handy!
Ned Gulley
Ned Gulley on 2 Dec 2025
I like the clear boundaries you draw between things that are good practices at any time and things that one should only do because it's useful in this quirky game called Cody. That's the right attitude, in my opinion! Cody is a place where it can be fun to flex and squirm in defiance of wise practice... but nobody is suggesting that's what you should do all the time. Still, I always learn new things watching people work, just as I learned some useful things from your list here!
Umar
Umar on 2 Dec 2025

Thank you @ WANG Zi-Xiang for this remarkably thorough and insightful reflection on Cody size optimization. Your post highlights something that often goes unacknowledged: once the basic task of “solving the problem” is complete, a second—and in many ways more intellectually playful—phase begins. The process of refining a solution under constraints such as code length invites a different mode of thinking, one that is both creative and analytical.

I particularly appreciate the way you frame these techniques as both instructive and, in some cases, intentionally non-portable to real-world programming practice. It takes a mature perspective to keep those boundaries clear. The contrast you draw between maintainable code and Cody-optimized code is a useful reminder that elegance can take multiple forms, depending on the aims of the task.

Your catalogue of strategies is invaluable. Many participants, especially newer solvers, may not realize how much MATLAB’s built-in functions can substitute for multi-line constructions, or how operator precedence and vectorization can be exploited to reduce syntactic overhead. The specific examples—such as replacing `x == 0` with `~x` or using `x.^0` instead of `ones(size(x))`—illustrate beautifully how one can re-imagine common operations through a size-minimization lens.

What stands out most in your post, however, is the overarching theme: that these optimizations cultivate a deeper understanding of the language itself. Constraints often reveal hidden structure, and your experience demonstrates how iterative refinement can uncover surprising efficiencies and novel solution pathways. The iterative “micro-experimentation” that Cody encourages can be intellectually generative in a way that traditional problem-solving sometimes is not.

Thank you for sharing both your techniques and your reflections. They will certainly be useful to others, and they also serve as a thoughtful meditation on the craft of writing concise, purposeful code.

WANG Zi-Xiang
WANG Zi-Xiang on 2 Dec 2025
Thanks Umar for your kind words and for perfectly pinpointing what I wished to emphasize! Couldn't have made my thoughts come through more clearly than you did 👍❤
Chen Lin
Chen Lin on 2 Dec 2025
Well said, @Umar. After the contest, outstanding articles like this should be organized and highlighted so future Cody solvers can easily read and learn from them.
Christopher Stapels
Christopher Stapels on 1 Dec 2025
Thanks for the tips! It would be interesting to see how the Cody rules would have to be written to avoid some of the things you say not to do in real code.
Vasilis Bellos
Vasilis Bellos on 1 Dec 2025
This is definitely a very interesting topic @WANG Zi-Xiang, and one that seems to go way back into the history of Cody and predates the time of many of us here, and which might trigger a trip down memory lane for some of the Cody veterans we've learned so much from.
You've put together a nice list of character-saving cases. I would definitely add the ans hack to the list. @Ned Gulley first posted about this (almost) a decade ago:
And somewhat more recently brought back the discussion on:
@John D'Errico also makes some very good points on the use of this hack here:
Whether we like it or not, it's one of the staple tricks along with regexp shenanigans (which has also been rightfully discussed very thoroughly, though for different reasons).
Interested to see where this conversation leads.
P.S. Congrats on squeezing @Stefan Abendroth et al.'s solution even further. Impressive!
Stefan Abendroth
Stefan Abendroth on 1 Dec 2025
Great summary and write-up! Sometimes (not always), reducing Cody size and actually improving the code are going hand in hand. I am regularly amazed how concise and beautiful some MATLAB solutions can get. My all-time champion on Cody is @Alfonso Nieto-Castanon. If you want to learn how to code in MATLAB, watch out for his solutions.

Tags

No tags entered yet.