How to reduce the Cody size of a solution
- Use this File Exchange submission to get the size of your solution: https://fr.mathworks.com/matlabcentral/fileexchange/34754-calculate-size
- Use existing MATLAB functions that may already perform the desired calculations but that you might have overlooked (as I did with histcount and digraph).
- Use vectorization amply. It’s what make the MATLAB language so concise and elegant!
- 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.
- Try writing out for loops instead of vectorization. Sometimes it’s actually smaller from a Cody point of view.
- 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!)
- 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!)
- Instead of variable assignments, write hardcoded constants. (Do not do this in real life!)
- 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).
- 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)
- Instead of x == -1, see if x < 0 works (smaller in size by 1).
- Instead of [1 2], write 1:2 (smaller in size by 1).
- “sum(sum(x))” is actually smaller than “sum(x, 1:2)”
- Instead of initialising a matrix of 2s with 2 * ones(m,n), write repmat(2,m,n) (smaller in size by 1).
- 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).
- Unfortunately, x ^-Inf doesn’t provide any reduction compared to zeros(size(x)), and it doesn’t work when x contains 0 or 1.
- 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).
12 Comments
Time Descending- using regexp to wrap code into a string without actually improving the code (e.g. https://de.mathworks.com/matlabcentral/cody/problems/43217-create-a-code-for-xnor/solutions/1148664)
- using eval or str2num to wrap expressions into a string
- https://blogs.mathworks.com/community/2016/06/23/the-great-ans-hack/
- and many others
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.