Main Content

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)
inv = 4
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)
ans = 1×1 cell array
{'563982230046568890902618956828002677439237127804414726979686441413745258166337260850508450357952871669760022932835205508650884432957132619548477681848951850249900098853578800502766453453321693488465782700659628264174757056271028413760264122292938046698234849427511943019674404460055307391183247077098238771593219759195361546550474847489454034087545485236581572021738623746876029952144698920606956981501906970107788143831844507572696523020854949377950584164671702209817937329138273107862450635272235829470591407489647002886722927663119075804284550987394985556133079386413055357606282374992498484308806888159999988894062720642359266610249180685549537651245402461171103020858571783996603386848039419656700597687469684534075920083663503623337165284634405944937809179503317603127766698557864519834438682815624108512662628659164318819211721788484510562704149517254432094419190323309859330458319203749328723347903942494042498481156385153413398528715754938381206379937482279105521608867050787631580424002980500346861332142946229358656510316436298104494540922341436539463379535760770882195633190667861276996489619134665056514210985714874297172396907228014612171439727292315001567764821061335577228917213918271255137714802428660758835259181668669987986012457471113553747414098971939000230951104638802770257722586728341096470806990469'}
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
  • = 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);
Steady-state temperature: 279.82 K
David Hill
David Hill
Last activity on 11 Nov 2025 at 21:29

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)
ans = 55
  • 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.
Visit https://oeis.org and paste the first few terms into the search bar.
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)
ans = 1×15
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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)
ans = '93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000'
David
David
Last activity on 20 Oct 2025 at 21:26

I just learned you can access MATLAB Online from the following shortcut in your web browser: https://matlab.new
We will be updating the MATLAB Answers infrastructure at 1PM EST today. We do not expect any disruption of service during this time. However, if you notice any issues, please be patient and try again later. Thank you for your understanding.
David
David
Last activity on 16 Oct 2024

We are happy to announce the addition of a new code analyzing feature to the AI Chat Playground. This new feature allows you to identify issues with your code making it easier to troubleshoot.
How does it work?
Just click the ANALYZE button in the toolbar of the code editor. Your code is sent to MATLAB running on a server which returns any warnings or errors, each of which are associated to a line of code on the right side of the editor window. Hover over each line marker to view the message.
Give it a try and share your feedback here. We will be adding this new capability to other community areas in the future so your feedback is appreciated.
Thank you,
David
Hello everyone,
Over the past few weeks, our community members have shared some incredible insights and resources. Here are some highlights worth checking out:

Interesting Questions

Johnathan is seeking help with implementing a complex equation into MATLAB's curve fitting toolbox. If you have experience with curve fitting or MATLAB, your input could be invaluable!

Popular Discussions

Athanasios continues his exploration of the Duffing Equation, delving into its chaotic behavior. It's a fascinating read for anyone interested in nonlinear dynamics or chaos theory.
John shares his playful exploration with MATLAB to find a generative equation for a sequence involving Fibonacci numbers. It's an intriguing challenge for those who love mathematical puzzles.

From File Exchange

Ayesha provides a graphical analysis of linearised models in epidemiology, offering a detailed look at the dynamics of these systems. This resource is perfect for those interested in mathematical modeling.
Gareth brings some humor to MATLAB with a toolbox designed to share jokes. It's a fun way to lighten the mood during conferences or meetups.

From the Blogs

Ned Gulley interviews Tim Marston, the 2023 MATLAB Mini Hack contest winner. Tim's creativity and skills are truly inspiring, and his story is a must-read for aspiring programmers.
Sivylla discusses the integration of AI with embedded systems, highlighting the benefits of using MATLAB and Simulink. It's an insightful read for anyone interested in the future of AI technology.
Thank you to all our contributors for sharing your knowledge and creativity. We encourage everyone to engage with these posts and continue fostering a vibrant and supportive community.
Happy exploring!
David
David
Last activity on 16 Sep 2024

Explore the newest online training courses, available as of 2024b: one new Onramp, eight new short courses, and one new learning path. Yes, that’s 10 new offerings. We’ve been busy.
As a reminder, Onramps are free to all. Short courses and learning paths require a subscription to the Online Training Suite (OTS).
  1. Multibody Simulation Onramp
  2. Analyzing Results in Simulink
  3. Battery Pack Modeling
  4. Introduction to Motor Control
  5. Signal Processing Techniques for Streaming Signals
  6. Core Signal Processing Techniques in MATLAB (learning path – includes the four short courses listed below)
Hello, MATLAB enthusiasts! 🌟
Over the past few weeks, our community has been buzzing with insightful questions, vibrant discussions, and innovative ideas. Whether you're a seasoned expert or a curious beginner, there's something here for everyone to learn and enjoy. Let's take a moment to highlight some of the standout contributions that have sparked interest and inspired many. Dive in and see how you can join the conversation or find solutions to your own challenges!

Interesting Questions

Oluwadamilola Oke is seeking assistance with a MATLAB code that works on version r2014b but encounters errors on version r2024a. The issue seems to be related to file location or the use of specific commands like movefile. If you have experience with these versions of MATLAB, your expertise could be invaluable.
Yohay has been working on a simulation to measure particle speed and fit it to the Maxwell-Boltzmann distribution. However, the fit isn't aligning perfectly with the data. Yohay has shared the code and histogram data for community members to review and provide suggestions.
Alessandro Livi is toggling between C++ for Arduino Pico and MATLAB App Designer. They suggest an enhancement where typing // for comments in MATLAB automatically converts to %. This small feature could improve the workflow for many users who switch between programming languages.

Popular Discussions

Athanasios Paraskevopoulos has started an engaging discussion on Gabriel's Horn, a shape with infinite surface area but finite volume. The conversation delves into the mathematical intricacies and integral calculations required to understand this paradoxical shape.
Honzik has brought up an interesting topic about custom fonts for MATLAB. While popular coding fonts handle characters like 0 and O well, they often fail to distinguish between different types of brackets. Honzik suggests that MathWorks could develop a custom font optimized for MATLAB syntax to reduce coding errors.

From the Blogs

Guy Rouleau addresses a common error in Simulink models: "Derivative of state '1' in block 'X/Y/Integrator' at time 0.55 is not finite." The blog post explores various tools and methods to diagnose and resolve this issue, making it a valuable read for anyone facing similar challenges.
Guest writer Gianluca Carnielli, featured by Adam Danz, shares insights on creating time-sensitive animations using MATLAB. The article covers controlling the motion of multiple animated objects, organizing data with timetables, and simplifying animations with the retime function. This is a must-read for anyone interested in scientific animations.
Feel free to check out these fascinating contributions and join the discussions! Your input and expertise can make a significant difference in our community.
Hello, everyone!
Over the past few weeks, our community has been buzzing with activity, showcasing the incredible depth of knowledge, creativity, and innovation that makes this forum such a vibrant place. Today, we're excited to highlight some of the noteworthy contributions that have sparked discussions, offered insights, and shared knowledge across various topics. Let's dive in!

Interesting Questions

Fatima Majeed brings us a thought-provoking mathematical challenge, delving into inequalities and the realms beyond (e^e). If you're up for a mathematical journey, this question is a must-see!
lil brain tackles a practical problem many of us have faced: efficiently segmenting a CSV file based on specific criteria. This post is not only a query but a learning opportunity for anyone dealing with similar data manipulation challenges.

Popular Discussions

Discover a simple yet effective trick for digit manipulation from goc3. This tip is especially handy for those frequenting Cody challenges or anyone interested in enhancing their number handling skills in MATLAB.
Chen Lin shares an exciting update about the 'Run Code' feature in the Discussions area, highlighting how our community can now directly execute and share code snippets within discussions. This feature marks a significant enhancement in how we interact and solve problems together.

From the Blogs

Connell D`Souza, alongside Team Swarthbeat, explores the cutting-edge application of EEG analysis in predicting neurological outcomes post-cardiac arrest. This blog post offers an in-depth look into the challenges and methodologies of modern medical data analysis.
Mihir Acharya discusses the pivotal role of MATLAB and Simulink in the future of robotics simulation. Through an engaging conversation with industry analyst George Chowdhury, this post sheds light on overcoming simulation challenges and the exciting possibilities that lie ahead.
We encourage everyone to explore these contributions further and engage with the authors and the community. Your participation is what fuels this community's continual growth and innovation.
Here's to many more discussions, discoveries, and breakthroughs together!
Hello MATLAB Community!
We've had an exciting few weeks filled with insightful discussions, innovative tools, and engaging blog posts from our vibrant community. Here's a highlight of some noteworthy contributions that have sparked interest and inspired us all. Let's dive in!

Interesting Questions

Cindyawati explores the intriguing concept of interrupting continuous data in differential equations to study the effects of drug interventions in disease models. A thought-provoking question that bridges mathematics and medical research.
Pedro delves into the application of Linear Quadratic Regulator (LQR) for error dynamics and setpoint tracking, offering insights into control systems and their real-world implications.

Popular Discussions

Chen Lin shares an engaging interview with Zhaoxu Liu, shedding light on the creative processes behind some of the most innovative MATLAB contest entries of 2023. A must-read for anyone looking for inspiration!
Zhaoxu Liu, also known as slanderer, updates the community with the latest version of the MATLAB Plot Cheat Sheet. This resource is invaluable for anyone looking to enhance their data visualization skills.

From File Exchange

Giorgio introduces a toolbox for frequency estimation, making it simpler for users to import signals directly from the MATLAB workspace. A significant contribution for signal processing enthusiasts.

From the Blogs

Cleve Moler revisits a classic program for predicting future trends based on census data, offering a fascinating glimpse into the evolution of computational forecasting.
With contributions from Dinesh Kavalakuntla, Adam presents an insightful guide on improving app design workflows in MATLAB App Designer, focusing on component swapping and labeling.
We're incredibly proud of the diverse and innovative contributions our community members make every day. Each post, discussion, and tool not only enriches our knowledge but also inspires others to explore and create. Let's continue to support and learn from each other as we advance in our MATLAB journey.
Happy Coding!
David
David
Last activity on 23 May 2024

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.
Hey MATLAB Community! 🌟
In the vibrant landscape of our online community, the past few weeks have been particularly exciting. We've seen a plethora of contributions that not only enrich our collective knowledge but also foster a spirit of collaboration and innovation. Here are some of the noteworthy contributions from our members.

Interesting Questions

Victor encountered a puzzling error while trying to publish his script to PDF. His post sparked a helpful discussion on troubleshooting this issue, proving invaluable for anyone facing similar challenges.
Devendra's inquiry into interpolating and smoothing NDVI time series using MATLAB has opened up a dialogue on various techniques to manage noisy data, benefiting researchers and enthusiasts in the field of remote sensing.

Popular Discussions

Adam Danz's AMA session has been a treasure trove of insights into the workings behind the MATLAB Answers forum, offering a unique perspective from a staff contributor's viewpoint.
The User Following feature marks a significant enhancement in how community members can stay connected with the contributions of their peers, fostering a more interconnected MATLAB Central.

From File Exchange

Robert Haaring's submission is a standout contribution, providing a sophisticated model for CO2 electrolysis, a topic of great relevance to researchers in environmental technology and chemical engineering.

From the Blogs

Sivylla's comprehensive post delves into the critical stages of AI model development, from implementation to validation, offering invaluable guidance for professionals navigating the complexities of AI verification.
In this engaging Q&A, Ned Gulley introduces us to Zhaoxu Liu, a remarkable community member whose innovative contributions and active engagement have left a significant impact on the MATLAB community.
Each of these contributions highlights the diverse and rich expertise within our community. From solving complex technical issues to introducing new features and sharing in-depth knowledge on specialized topics, our members continue to make MATLAB Central a vibrant and invaluable resource.
Let's continue to support, inspire, and learn from one another
Hey MATLAB Community! 🌟
As we continue to explore, learn, and innovate together, it's essential to take a moment to recognize the remarkable contributions that have sparked engaging discussions, solved perplexing problems, and shared insightful knowledge in the past two weeks. Let's dive into the highlights that have made our community even more vibrant and resourceful.

Interesting Questions

Burhan Burak brings up an intriguing issue faced when running certain code in MATLAB, seeking advice on how to refactor the code to eliminate a warning message. It's a great example of the practical challenges we often encounter
Jenni asks for guidance on improving linear models to fit data points more accurately. This question highlights the common hurdles in data analysis and model fitting, sparking a conversation on best practices and methodologies.

Popular Discussions

A thought-provoking question posed by goc3 that delves into the intricacies of MATLAB's logical operations. It's a great discussion starter that tests and expands our understanding of MATLAB's behavior.
Toshiaki Takeuchi shares an insightful visualization of the demand for MATLAB jobs across different regions, based on data from LinkedIn. This post not only provides a snapshot of the job market but also encourages members to discuss trends in MATLAB's use in the industry.

From the Blogs

Mike Croucher shares his excitement and insights on two long-awaited features finally making their way into MATLAB R2024a. His post reflects the passion and persistence of our community members in enhancing MATLAB's functionality.
In this informative post, Sivylla Paraskevopoulou offers practical tips for speeding up the training of deep learning models. It's a must-read for anyone looking to optimize their deep learning workflows.
A Heartfelt Thank You 🙏
To everyone who asked a question, started a discussion, or wrote a blog post: Thank you! Your contributions are what make our community a fountain of knowledge, inspiration, and innovation. Let's keep the momentum going and continue to support each other in our journey to explore the vast universe of MATLAB.
Happy Coding!
Note: If you haven't yet, make sure to check out these highlights and add your voice to our growing community. Your insights and experiences are what make us stronger.
Hello, brilliant minds of our engineering community!
We hope this message finds you in the midst of an exciting project or, perhaps, deep in the realms of a challenging problem, because we've got some groundbreaking news that might just make your day a whole lot more interesting.
🎉 Introducing PreAnswer AI - The Future of Community Support! 🎉
Have you ever found yourself pondering over a complex problem, wishing for an answer to magically appear before you even finish formulating the question? Well, wish no more! The MathWorks team, in collaboration with the most imaginative minds from the realms of science fiction, is thrilled to announce the launch of PreAnswer AI, an unprecedented feature set to revolutionize the way we interact within our MATLAB and Simulink community.
What is PreAnswer AI?
PreAnswer AI is our latest AI-driven initiative designed to answer your questions before you even ask them. Yes, you read that right! Through a combination of predictive analytics, machine learning, and a pinch of engineering wizardry, PreAnswer AI anticipates the challenges you're facing and provides you with solutions, insights, and code snippets in real-time.
How Does It Work?
  • Presentiment Algorithms: By simply logging into MATLAB Central, our AI begins to analyze your recent coding patterns, activity, and even the intensity of your keyboard strokes to understand your current state of mind.
  • Predictive Insights: Using a complex algorithm, affectionately dubbed "The Oracle", PreAnswer AI predicts the questions you're likely to ask and compiles comprehensive answers from our vast database of resources.
  • Efficiency and Speed: Imagine the time saved when the answers to your questions are already waiting for you. PreAnswer AI ensures you spend more time innovating and less time searching for solutions.
We are on the cusp of deploying PreAnswer AI in a beta phase and are eager for you to be among the first to experience its benefits. Your feedback will be invaluable as we refine this feature to better suit our community's needs.
---------------------------------------------------------------
Spoiler, it's April 1st if you hadn't noticed. While we might not (yet) have the technology to read minds or predict the future, we do have an incredible community filled with knowledgeable, supportive members ready to tackle any question you throw their way.
Let's continue to collaborate, innovate, and solve complex problems together, proving that while AI can do many things, the power of a united community of brilliant minds is truly unmatched.
Thank you for being such a fantastic part of our community. Here's to many more questions, answers, and shared laughs along the way.
Happy April Fools' Day!