Results for
Many MATLAB Cody problems involve solving congruences, modular inverses, Diophantine equations, or simplifying ratios under constraints. A powerful tool for these tasks is the Extended Euclidean Algorithm (EEA), which not only computes the greatest common divisor, gcd(a,b), but also provides integers x and y such that: a*x + b*y = gcd(a,b) - which is Bezout's identity.
Use of the Extended Euclidean Algorithm is very using in solving many different types of MATLAB Cody problems such as:
- Computing modular inverses safely, even for very large numbers
- Solving linear Diophantine equations
- Simplifing fractions or finding nteger coefficients without using symbolic tools
- Avoiding loops (EEA can be implemented recursively)
Below is a recursive implementation of the EEA.
function [g,x,y] = egcd(a,b)
% a*x + b*y = g [gcd(a,b)]
if b == 0
g = a; x = 1; y = 0;
else
[g, x1, y1] = egcd(b, mod(a,b));
x = y1;
y = x1 - floor(a/b)*y1;
end
end
Problem:
Given integers a and m, return the modular inverse of a (mod m).
If the inverse does not exist, return -1.
function inv = modInverse(a,m)
[g,x,~] = egcd(a,m);
if g ~= 1 % inverse doesn't exist
inv = -1;
else
inv = mod(x,m); % Bézout coefficient gives the inverse
end
end
%find the modular inverse of 19 (mod 5)
inv=modInverse(19,5)
When solving Cody problems, sometimes your solution takes too long — especially if you’re recomputing large arrays or iterative sequences every time your function is called.
The Cody work area resets between separate runs of your code, but within one Cody test suite, your function may be called multiple times in a single session.
This is where persistent variables come in handy.
A persistent variable keeps its value between function calls, but only while MATLAB is still running your function suite.
This means:
- You can cache results to avoid recomputation.
- You can accumulate data across multiple calls.
- But it resets when Cody or MATLAB restarts.
Suppose you’re asked to find the n-th Fibonacci number efficiently — Cody may time out if you use recursion naively. Here’s how to use persistent to store computed values:
function f = fibPersistent(n)
import java.math.BigInteger
persistent F
if isempty(F)
F=[BigInteger('0'),BigInteger('1')];
for k=3:10000
F(k)=F(k-1).add(F(k-2));
end
end
% Extend the stored sequence only if needed
while length(F) <= n
F(end+1)=F(end).add(F(end-1));
end
f = char(F(n+1).toString); % since F(1) is really F(0)
end
%calling function 100 times
K=arrayfun(@(x)fibPersistent(x),randi(10000,1,100),'UniformOutput',false);
K(100)
The fzero function can handle extremely messy equations — even those mixing exponentials, trigonometric, and logarithmic terms — provided the function is continuous near the root and you give a reasonable starting point or interval.
It’s ideal for cases like:
- Solving energy balance equations
- Finding intersection points of nonlinear models
- Determining parameters from experimental data
Example: Solving for Equilibrium Temperature in a Heat Radiation-Conduction Model
Suppose a spacecraft component exchanges heat via conduction and radiation with its environment. At steady state, the power generated internally equals the heat lost:
Given constants:
= 25 W- k = 0.5 W/K
- ϵ = 0.8
- σ = 5.67e−8 W/m²K⁴
- A = 0.1 m²
= 250 K
Find the steady-state temperature, T.
% Given constants
Qgen = 25;
k = 0.5;
eps = 0.8;
sigma = 5.67e-8;
A = 0.1;
Tinf = 250;
% Define the energy balance equation (set equal to zero)
f = @(T) Qgen - (k*(T - Tinf) + eps*sigma*A*(T.^4 - Tinf^4));
% Plot for a sense of where the root lies before implementing
fplot(f, [250 300]); grid on
xlabel('Temperature (K)'); ylabel('f(T)')
title('Energy Balance: Root corresponds to steady-state temperature')
% Use fzero with an interval that brackets the root
T_eq = fzero(f, [250 300]);
fprintf('Steady-state temperature: %.2f K\n', T_eq);
I set my 3D matrix up with the players in the 3rd dimension. I set up the matrix with: 1) player does not hold the card (-1), player holds the card (1), and unknown holding the card (0). I moved through the turns (-1 and 1) that are fixed first. Then cycled through the conditional turns (0) while checking the cards of each player using the hints provided until it was solved. The key for me in solving several of the tests (11, 17, and 19) was looking at the 1's and 0's being held by each player.
sum(cardState==1,3);%any zeros in this 2D matrix indicate possible cards in the solution
sum(cardState==0,3)>0;%the ones in this 2D matrix indicate the only unknown positions
sum(cardState==1,3)|sum(cardState==0,3)>0;%oring the two together could provide valuable information
Some MATLAB Cody problems prohibit loops (for, while) or conditionals (if, switch, while), forcing creative solutions.
One elegant trick is to use nested functions and recursion to achieve the same logic — while staying within the rules.
Example: Recursive Summation Without Loops or Conditionals
Suppose loops and conditionals are banned, but you need to compute the sum of numbers from 1 to n. This is a simple example and obvisously n*(n+1)/2 would be preferred.
function s = sumRecursive(n)
zero=@(x)0;
s = helper(n); % call nested recursive function
function out = helper(k)
L={zero,@helper};
out = k+L{(k>0)+1}(k-1);
end
end
sumRecursive(10)
- The helper function calls itself until the base case is reached.
- Logical indexing into a cell array (k>0) act as an 'if' replacement.
- MATLAB allows nested functions to share variables and functions (zero), so you can keep state across calls.
Tips:
- Replace 'if' with logical indexing into a cell array.
- Replace for/while with recursion.
- Nested functions are local and can access outer variables, avoiding global state.
Many MATLAB Cody problems involve recognizing integer sequences.
If a sequence looks familiar but you can’t quite place it, the On-Line Encyclopedia of Integer Sequences (OEIS) can be your best friend.
OEIS will often identify the sequence, provide a formula, recurrence relation, or even direct MATLAB-compatible pseudocode.
Example: Recognizing a Cody Sequence
Suppose you encounter this sequence in a Cody problem:
1, 1, 2, 3, 5, 8, 13, 21, ...
Entering it on OEIS yields A000045 – The Fibonacci Numbers, defined by:
F(n) = F(n-1) + F(n-2), with F(1)=1, F(2)=1
You can then directly implement it in MATLAB:
function F = fibSeq(n)
F = zeros(1,n);
F(1:2) = 1;
for k = 3:n
F(k) = F(k-1) + F(k-2);
end
end
fibSeq(15)
When solving MATLAB Cody problems involving very large integers (e.g., factorials, Fibonacci numbers, or modular arithmetic), you might exceed MATLAB’s built-in numeric limits.
To overcome this, you can use Java’s java.math.BigInteger directly within MATLAB — it’s fast, exact, and often accepted by Cody if you convert the final result to a numeric or string form.
Below is an example of using it to find large factorials.
function s = bigFactorial(n)
import java.math.BigInteger
f = BigInteger('1');
for k = 2:n
f = f.multiply(BigInteger(num2str(k)));
end
s = char(f.toString); % Return as string to avoid overflow
end
bigFactorial(100)
I just learned you can access MATLAB Online from the following shortcut in your web browser: https://matlab.new
Thanks @Yann Debray
From his recent blog post: pip & uv in MATLAB Online » Artificial Intelligence - MATLAB & Simulink
Share your ideas, suggestions, and wishlists for improving MathWorks products. What would make the software absolutely perfect for you? Discuss your idea(s) with other community users.
Guidelines & Tips
We encourage all ideas, big or small! To help everyone understand and discuss your suggestion, please include as much detail as possible in your post:
- Product or Feature: Clearly state which product (e.g., MATLAB, Simulink, a toolbox, etc.) or specific feature your idea relates to.
- The Problem or Opportunity: Briefly describe what challenge you’re facing or what opportunity you see for improvement.
- Your Idea: Explain your suggestion in detail. What would you like to see added, changed, or improved? How would it help you and other users?
- Examples or Use Cases (optional): If possible, include an example, scenario, or workflow to illustrate your idea.
- Related Posts (optional): If you’ve seen similar ideas or discussions, feel free to link to them for context.
Ready to share your idea?
Click here and then "Start a Discussion”, and let the community know how MATLAB could be even better for you!
Thank you for your contributions and for helping make MATLAB Central a vibrant place for sharing and improving ideas.
I saw this on Reddit and thought of the past mini-hack contests. We have a few folks here who can do something similar with MATLAB.
In case you haven't come across it yet, @Gareth created a Jokes toolbox to get MATLAB to tell you a joke.
A colleague said that you can search the Help Center using the phrase 'Introduced in' followed by a release version. Such as, 'Introduced in R2022a'. Doing this yeilds search results specific for that release.
Seems pretty handy so I thought I'd share.

A bit late. Compliments to Chris for sharing.
Unlike last year's contest, there are some new technologies this year that might offer some advantages. Namely generative AI's like ChatGPT, Bard, etc. Not to be excluded, MathWorks just launched the AI Chat Playground :)
Here's a MATLAB class I wrote that leverages the MATLAB Central Interface for MATLAB toolbox, which in turn uses the publicy available Community API. Using this class, I've created a few Favorites that show me what's going on in MATLAB Central - without having to leave MATLAB 🙂
The class has a few convenient queries:
- Results for the last 7 days
- Results for the last 30 days
- Results for the current month
- Results for today
And supporting a bunch of different content scopes:
- All MATLAB Central
- MATLAB Answers
- Blogs
- Cody
- Contests
- File Exchange
- Exclude Answers content
The results are displayed in the command window (which worked best for me) and link to each post. Here's what that looks like for this command
>> CommunityFeed.thisMonth("app designer", CommunityFeed.Scope.ExcludeAnswers)

Let me know if you find this class useful and feel free to suggest changes.
The contest development team has identified an issue when trying to link your new entries to submissions in the File Exchange. The issue has prevented some users from successfully linking their entries. We have a fix and will be deploying it today at 3pm EST.
