Give your LLM an easier time looking for information on mathworks.com: point it to the recently released llms.txt files. The top-level one is www.mathworks.com/llms.txt, release changes use www.mathworks.com/help/relnotes. How does it work for you??
(Requested for newer MATLAB releases (e.g. R2026B), MATLAB Parallel Processing toolbox.)
Lower precision array types have been gaining more popularity over the years for deep learning. The current lowest precision built-in array type offered by MATLAB are 8-bit precision arrays, e.g. int8 and uint8. A good thing is that these 8-bit array types do have gpuArray support, meaning that one is able to design GPU MEX codes that take in these 8-bit arrays and reinterpret them bit-wise as other 8-bit array types, e.g. FP8, which is especially common array type used in modern day deep learning applications. I myself have used this to develop forward pass operations with 8-bit precision that are around twice as fast as 16-bit operations and with output arrays that still agree well with 16-bit outputs (measured with high cosine similarity). So the 8-bit support that MATLAB offers is already quite sufficient.
Recently, 4-bit precision array types have been shown also capable of being very useful in deep learning. These array types can be processed with Tensor Cores of more modern GPUs, such as NVIDIA's Blackwell architecture. However, MATLAB does not yet have a built-in 4-bit precision array type.
Just like MATLAB has int8 and uint8, both also with gpuArray support, it would also be nice to have MATLAB have int4 and uint4, also with gpuArray support.
Mike Croucher
Mike Croucher
Última actividad el 16 de Dic. de 2025 a las 14:26

I thought it would be fun to vibe code Christmas trees.
Model: Claude Sonnet4.5
Prompt: Write a MATLAB script that draws a Christmas tree. There should be decorations and presents too.
Result:
christmasTree()
function christmasTree()
% Christmas Tree with Decorations and Presents
% Creates a festive scene with a decorated tree and gift boxes
figure('Color', 'w', 'Position', [100, 100, 800, 900]);
hold on;
axis equal;
axis off;
xlim([-3, 3]);
ylim([0, 10]);
% Draw the tree (three layered triangular sections)
drawTreeSection(0, 2, 2.5, 2.5, [0.1, 0.5, 0.1]);
drawTreeSection(0, 3.5, 2, 2, [0.15, 0.55, 0.15]);
drawTreeSection(0, 4.8, 1.5, 1.8, [0.2, 0.6, 0.2]);
% Tree trunk
rectangle('Position', [-0.3, 0, 0.6, 2], 'FaceColor', [0.4, 0.2, 0.1], ...
'EdgeColor', 'none');
% Add decorations
addOrnaments();
addTinsel();
% Star on top
drawStar(0, 7.2, 0.4, [1, 0.84, 0]);
% Add presents under the tree
drawPresent(-1.8, 0, 0.6, 0.5, [0.8, 0.1, 0.1], [1, 0.84, 0]);
drawPresent(-0.8, 0, 0.5, 0.6, [0.1, 0.3, 0.8], [0.9, 0.9, 0.9]);
drawPresent(1.2, 0, 0.7, 0.4, [0.7, 0.5, 0.9], [0.2, 0.8, 0.2]);
drawPresent(0.2, 0, 0.4, 0.5, [1, 0.7, 0.1], [0.8, 0.1, 0.1]);
% Add some snow on the ground
scatter(randn(1, 100)*2.5, rand(1, 100)*0.3, 20, 'w', 'filled', ...
'MarkerEdgeColor', [0.8, 0.8, 0.8]);
title('Merry Christmas!', 'FontSize', 24, 'Color', [0.8, 0.1, 0.1], ...
'FontWeight', 'bold');
hold off;
end
function drawTreeSection(x, y, width, height, color)
% Draw a triangular section of the tree
xPoints = [x - width, x + width, x];
yPoints = [y, y, y + height];
fill(xPoints, yPoints, color, 'EdgeColor', [0.05, 0.3, 0.05], ...
'LineWidth', 1.5);
end
function addOrnaments()
% Add colorful baubles to the tree
ornamentColors = [
1, 0, 0; % Red
0, 0, 1; % Blue
1, 0.84, 0; % Gold
0.9, 0.1, 0.5;% Pink
0.5, 0, 0.5 % Purple
];
% Ornament positions (x, y coordinates)
positions = [
-1.5, 2.5; 1.5, 2.5; 0, 3.2;
-1.2, 3.8; 1.2, 3.8; -0.6, 4.2; 0.6, 4.2;
-0.8, 5.2; 0.8, 5.2; 0, 5.8; -0.4, 6.3; 0.4, 6.3
];
for i = 1:size(positions, 1)
colorIdx = mod(i-1, size(ornamentColors, 1)) + 1;
x = positions(i, 1);
y = positions(i, 2);
% Draw bauble
theta = linspace(0, 2*pi, 50);
radius = 0.15;
xCirc = x + radius * cos(theta);
yCirc = y + radius * sin(theta);
fill(xCirc, yCirc, ornamentColors(colorIdx, :), ...
'EdgeColor', ornamentColors(colorIdx, :)*0.7, 'LineWidth', 1.5);
% Add highlight for shine
highlightX = x - radius*0.4 + radius*0.3*cos(theta(1:15));
highlightY = y + radius*0.4 + radius*0.3*sin(theta(1:15));
fill(highlightX, highlightY, [1, 1, 1], 'EdgeColor', 'none', ...
'FaceAlpha', 0.6);
end
end
function addTinsel()
% Add sparkly tinsel effect
tinselX = [-1.8, -1.2, -0.5, 0.2, 0.9, 1.6];
tinselY = [2.8, 3.5, 4.0, 4.5, 5.0, 5.5];
for i = 1:length(tinselX)
plot(tinselX(i) + randn(1, 5)*0.1, tinselY(i) + rand(1, 5)*0.2, ...
'*', 'Color', [1, 0.84, 0], 'MarkerSize', 8, 'LineWidth', 1.5);
end
end
function drawStar(x, y, size, color)
% Draw a 5-pointed star on top of the tree
angles = linspace(0, 2*pi, 11);
radii = repmat([size, size*0.4], 1, 5);
radii = [radii, radii(1)];
xStar = x + radii .* cos(angles - pi/2);
yStar = y + radii .* sin(angles - pi/2);
fill(xStar, yStar, color, 'EdgeColor', [0.8, 0.6, 0], 'LineWidth', 2);
% Add sparkle
plot(x, y, '*', 'Color', [1, 1, 1], 'MarkerSize', 15, 'LineWidth', 2);
end
function drawPresent(x, y, width, height, boxColor, ribbonColor)
% Draw a gift box with ribbon and bow
% Box
rectangle('Position', [x, y, width, height], 'FaceColor', boxColor, ...
'EdgeColor', boxColor*0.7, 'LineWidth', 2);
% Vertical ribbon
ribbonWidth = width * 0.15;
rectangle('Position', [x + width/2 - ribbonWidth/2, y, ribbonWidth, height], ...
'FaceColor', ribbonColor, 'EdgeColor', 'none');
% Horizontal ribbon
ribbonHeight = height * 0.15;
rectangle('Position', [x, y + height/2 - ribbonHeight/2, width, ribbonHeight], ...
'FaceColor', ribbonColor, 'EdgeColor', 'none');
% Bow on top
bowX = x + width/2;
bowY = y + height;
bowSize = width * 0.2;
% Left loop
theta = linspace(0, pi, 30);
fill(bowX - bowSize*0.3 + bowSize*0.5*cos(theta), ...
bowY + bowSize*0.5*sin(theta), ribbonColor, 'EdgeColor', 'none');
% Right loop
fill(bowX + bowSize*0.3 + bowSize*0.5*cos(theta), ...
bowY + bowSize*0.5*sin(theta), ribbonColor, 'EdgeColor', 'none');
% Center knot
theta = linspace(0, 2*pi, 30);
fill(bowX + bowSize*0.25*cos(theta), bowY + bowSize*0.25*sin(theta), ...
ribbonColor*0.8, 'EdgeColor', 'none');
end
Peter
Peter
Última actividad el 15 de Dic. de 2025 a las 19:15

Hi everyone
I've been using ThingSpeak for several years now without an issue until last Thursday.
I have four ThingSpeak channels which are used by three Arduino devices (in two locations/on two distinct networks) all running the same code.
All three devices stopped being able to write data to my ThingSpeak channels around 17:00 CET on 4 Dec and are still unable to.
Nothing changed on this side, let alone something that would explain the problem.
I would note that data can still be written to all the channels via a browser so there is no fundamental problem with the channels (such as being full).
Since the above date and time, any HTTP/1.1 'update' (write) requests via the REST API (using both simple one-write GET requests or bulk JSON POST requests) are timing out after 5 seconds and no data is being written. The 5 second timeout is my Arduino code's default, but even increasing it to 30 seconds makes no difference. Before all this, responses from ThingSpeak were sub-second.
I have recompiled the Arduino code using the latest libraries and that didn't help.
I have tested the same code again another random api (api.ipify.org) and that works just fine.
Curl works just fine too, also usng HTTP/1.1
So the issue appears to be something particular to the combination of my Arduino code *and* the ThingSpeak environment, where something changed on the ThingSpeak end at the above date and time.
If anyone in the community has any suggestions as to what might be going on, I would greatly appreciate the help.
Peter
I like this quote, what do you think?
"If the part of programming you enjoy most is the physical act of writing code, then agents will feel beside the point. You’re already where you want to be, even just with some Copilot or Cursor-style intelligent code auto completion, which makes you faster while still leaving you fully in the driver’s seat about the code that gets written.
But if the part you care about is the decision-making around the code, agents feel like they clear space. They take care of the mechanical expression and leave you with judgment, tradeoffs, and intent. Because truly, for someone at my experience level, that is my core value offering anyway. When I spend time actually typing code these days with my own fingers, it feels like a waste of my time."
— Obie Fernandez, What happens when the coding becomes the least interesting part of the work
Matt Tearle
Matt Tearle
Última actividad el 13 de Dic. de 2025 a las 11:50

Fittingly for a Creative Coder, @Vasilis Bellos clearly enjoyed the silliness I put into the problems. If you've solved the whole problem set, don't forget to help out your teammates with suggestions, tips, tricks, etc. But also, just for fun, I'm curious to see which of my many in-jokes and nerdy references you noticed. Many of the problems were inspired by things in the real world, then ported over into the chaotic fantasy world of Nedland.
I guess I'll start with the obvious real-world reference: @Ned Gulley (I make no comment about his role as insane despot in any universe, real or otherwise.)
Chen Lin
Chen Lin
Última actividad el 13 de Dic. de 2025 a las 7:47

The Cody Contest 2025 has officially wrapped up! Over the past 4 weeks, more than 700 players submitted over 20,000 solutions. In addition, participants shared 20+ high-quality Tips & Tricksarticles—resources that will benefit Cody users for years to come.
Now it’s time to announce the winners.
🎉 Week 4 winners:
Weekly Prizes for Contest Problem Group Finishers:
Weekly Prizes for Contest Problem Group Solvers:
Weekly Prizes for Tips & Tricks Articles:
This week’s prize goes to @WANG Zi-Xiang. See the comments from our judge and problem group author @Matt Tearle:
‘We had a lot of great tips for solving Cody problems in general and the contest problems specifically. But we all know there are those among us who, having solved the problem, still want to tinker and make their code better. There are different definitions of "better", but code size remains the base metric in Cody. Enter Wang Zi-Xiang who compiled a list of many tips for reducing Cody size. This post also generated some great discussion (even prompting our insane autocrat, Lord Ned himself, to chime in). I particularly like the way that, while reducing Cody size often requires some arcane tricks that would normally be considered bad coding practice, the intellectual activity of trying to "game the system" makes you consider different programming approaches, and sometimes leads you to learn corners of MATLAB that you didn't know.’
🏆 Grand Prizes for the Main Round
Team Relentless Coders:
1st Place: @Boldizsar
2nd Place: @Roberto
Team Creative Coders:
1st Place: @Mehdi Dehghan
2nd Place: @Vasilis Bellos
3rd Place: @Alaa
Team Cool Coders
1st Place: @Hong Son
2nd Place: @Norberto
3rd Place: @Maxi
Congratulations to all! Securing a top position on the leaderboard requires not only advanced MATLAB skills but also determination and consistency throughout the four-week contest. You will receive Amazon gift cards.
🥇 Winning Team
The competition was incredibly tight—we even had to use the tie-breaker rule.
Both Team Cool Coders and Team Relentless Coders achieved 16 contest group finishers. However, the last finisher on Cool Coders completed the problem group at 1:02 PM on Dec 7, while the last finisher on Relentless Coders finished at 9:47 PM the same day.
Such a close finish! Congratulations to Team Cool Coders, who have earned the Winning Team Finishers badge.
🎬 Bonus Round
Invitations have been sent to the 6 players who qualified for the Bonus Round. Stay tuned for updates—including the Big Watch Party afterward!
Congratulations again to all winners! We’ll be reaching out after the contest ends. It has been an exciting, rewarding, and knowledge-packed journey.
See you next year!
As far as I know, the MATLAB Community (including Matlab Central and Mathworks' official GitHub repository) has always been a vibrant and diverse professional and amateur community of MATLAB users from various fields globally. Being a part of it myself, especially in recent years, I have not only benefited continuously from the community but also tried to give back by helping other users in need.
I am a senior MATLAB user from Shenzhen, China, and I have a deep passion for MATLAB, applying it in various scenarios. Due to the less than ideal job market in my current social environment, I am hoping to find a position for remote support work within the Matlab Community. I wonder if this is realistic. For instance, Mathworks has been open-sourcing many repositories in recent years, especially in the field of deep learning with typical applications across industries. I am eager to use the latest MATLAB features to implement state-of-the-art algorithms. Additionally, I occasionally contribute through GitHub issues and pull requests.
In conclusion, I am looking forward to the opportunity to formally join the Matlab Community in a remote support role, dedicating more energy to giving back to the community and making the world a better place! (If a Mathworks employer can contact me, all the better~)
Book Program
Book Program
Última actividad el 11 de Dic. de 2025 a las 17:29

Hello! The MathWorks Book Program is thrilled to welcome you to our discussion channel dedicated to books on MATLAB and Simulink. Here, you can:
  • Promote Your Books: Are you an author of a book on MATLAB or Simulink? Feel free to share your work with our community. We’re eager to learn about your insights and contributions to the field.
  • Request Recommendations: Looking for a book on a specific topic? Whether you're diving into advanced simulations or just starting with MATLAB, our community is here to help you find the perfect read.
  • Ask Questions: Curious about the MathWorks Book Program, or need guidance on finding resources? Post your questions and let our knowledgeable community assist you.
We’re excited to see the discussions and exchanges that will unfold here. Whether you're an expert or beginner, there's a place for you in our community. Let's embark on this journey together!

Building Transition Matrices for the Royal Game of Err

King Neduchadneddar the Procrastinator has devised yet another scheme to occupy his court's time, and this one is particularly devious. The Royal Game of Err involves moving pawns along a path of n squares by rolling an m-sided die, with forbidden squares thrown in just to keep things interesting. Your mission, should you choose to accept it, is to construct a transition matrix that captures all the probabilistic mischief of this game. But here's the secret: you don't need nested loops or brute force. With the right MATLAB techniques, you can build this matrix with the elegance befitting a Chief Royal Mage of Matrix Computations.

The heart of this problem lies in recognizing that the transition matrix is dominated by a beautiful superdiagonal pattern. When you're on square j and roll the die, you have a 1/m chance of moving to each of squares j+1, j+2, up to j+m, assuming none are forbidden and you don't overshoot. This screams for vectorized construction rather than element-by-element assignment. The key weapon in your arsenal is MATLAB's ability to construct multiple diagonals simultaneously using either repeated calls to diag with offset parameters, or the more powerful spdiags function for those comfortable with advanced matrix construction.

Consider this approach: start with a zero matrix and systematically add 1/m to each of the m superdiagonals. For a die with m sides, you're essentially saying "from square j, there's a 1/m probability of landing on j+k for k = 1 to m." This can be accomplished with a simple loop over k, using T = T + diag(ones(1,n-k)*(1/m), k) for each offset k from 1 to m. The beauty here is that you're working with entire diagonals at once, not individual elements. This vectorized approach is not only more elegant but also more efficient and less error-prone than tracking indices manually.

Figure 1: Basic transition matrix structure for n=8, m=3, no forbidden squares. Notice the three superdiagonals carrying probability 1/3 each.

Now comes the interesting part: handling forbidden squares. When square j is forbidden, two things must happen simultaneously. First, you cannot land ON square j from anywhere, which means column j should be entirely zeros. Second, you cannot move FROM square j to anywhere, which means row j should be entirely zeros. The naive approach would involve checking each forbidden square and carefully adjusting individual elements. The elegant approach recognizes that MATLAB's logical indexing was practically designed for this scenario.

Here's the trick: once you've built your basic superdiagonal structure, handle all forbidden squares in just two lines: T(nogo, :) = 0 to eliminate all moves FROM forbidden squares, and T(:, nogo) = 0 to eliminate all moves TO forbidden squares. But wait, there's more. When you zero out these entries, the probabilities that would have gone to those squares need to be redistributed. This is where the "stay put" mechanism comes in. If rolling a 3 would land you on a forbidden square, you stay where you are instead. This means adding those lost probabilities back to the main diagonal.

The sophisticated approach uses logical indexing to identify which transitions would have violated the forbidden square rule, then redirects those probabilities to the diagonal. You can check if a move from square j to square k would hit a forbidden square using ismember(k, nogo), and if so, add that 1/m probability to T(j,j) instead. This "probability conservation" ensures that each row still sums to 1, maintaining the stochastic property of your transition matrix.

Figure 2: Transition matrix with forbidden squares marked. Left: before adjustment. Right: after forbidden square handling showing probability redistribution. Compare the diagonal elements.

The final square presents its own challenge. Once you reach square n, the game is over, which in Markov chain terminology means it's an "absorbing state." This is elegantly represented by setting T(n,n) = 1 and ensuring T(n, j) = 0 for all j not equal to n. But there's another boundary condition that's equally important: what happens when you're on square j and rolling the die would take you beyond square n?

The algorithm description provides a clever solution: you stay put. If you're on square n-2 and roll a 4 on a 6-sided die, you don't move. This means that for squares near the end, the diagonal element T(j,j) needs to accumulate probability from all those "overshooting" scenarios. Mathematically, if you're on square j and rolling k where j+k exceeds n, that 1/m probability needs to be added to T(j,j). A clean way to implement this is to first build the full superdiagonal structure as if the board were infinite, then add (1:m)/m to the last m elements of the diagonal to account for staying put.

There's an even more elegant approach: build your superdiagonals only up to where they're valid, then explicitly calculate how much probability should stay on the diagonal for each square. For square j, count how many die outcomes would either overshoot n or hit forbidden squares, multiply by 1/m, and add to T(j,j). This direct calculation ensures you've accounted for every possible outcome and maintains the row-sum property.

Figure 3: Heat map showing probability distributions from different starting squares. Notice how probabilities "pile up" at the diagonal for squares near the boundary.

Now that you understand the three key components, the construction strategy becomes clear. Initialize your n-by-n zero matrix. Build the basic superdiagonal structure to represent normal movement. Identify and handle forbidden squares by zeroing rows and columns, then redistributing lost probability to the diagonal. Finally, ensure boundary conditions are met by setting the final square as absorbing and handling the "stay put" cases for near-boundary squares.

The order matters here. If you handle forbidden squares first and then build diagonals, you might overwrite your forbidden square adjustments. The cleanest approach is to build all m superdiagonals first, then make a single pass to handle both forbidden squares and boundary conditions simultaneously. This can be done efficiently with a vectorized check: for each square j, count valid moves, calculate stay-put probability, and update T(j,j) accordingly.

Figure 4: Complete transition matrix for a test case with n=7, m=4, nogo=[2 5]. Spy plot showing the sparse structure alongside a color-coded heat map. Notice the complex pattern of probabilities.

Before declaring victory over King Neduchadneddar, verify your matrix satisfies the fundamental properties of a transition matrix. First, every element should be between 0 and 1 (probabilities, after all). Second, each row should sum to exactly 1, representing the fact that from any square, you must end up somewhere (even if it's staying put). You can check this with all(abs(sum(T,2) - 1) < 1e-10) to account for floating-point arithmetic.

The provided test cases offer another validation opportunity. Start with the simplest cases where patterns are obvious, like n=8, m=3 with no forbidden squares. You should see a clean superdiagonal structure. Then progress to cases with forbidden squares and verify that columns and rows are properly zeroed. The algorithm description even provides example matrices for you to compare against. Pay special attention to the diagonal elements, as they're where most of the complexity hides.

Figure 5: Validation dashboard showing row sums (should all be 1), matrix properties, and comparison with expected structure for a simple test case.

For those seeking to optimize their solution, consider that for large n, explicitly storing an n-by-n dense matrix becomes memory-intensive. Since most elements are zero, MATLAB's sparse matrix format is ideal. Replace zeros(n) with sparse(n,n) at initialization. The same indexing and diagonal operations work seamlessly with sparse matrices, but you'll save considerable memory for large problems.

Another sophistication involves recognizing that the transition matrix construction is fundamentally about populating a banded matrix with some modifications. The spdiags function was designed for exactly this scenario. You can construct all m superdiagonals in a single call by preparing a matrix where each column represents one diagonal's values. While the syntax takes some getting used to, the resulting code is remarkably compact and efficient.

For debugging purposes, visualizing your matrix at each construction stage helps immensely. Use imagesc(T) with a colorbar to see the probability distribution, or spy(T) to see the non-zero structure. If you're not seeing the expected patterns, these visualizations immediately reveal whether your diagonals are in the right positions or if forbidden squares are properly handled.

Figure 6: Performance comparison showing construction time and memory usage for dense vs sparse implementations as n increases.

King Neduchadneddar may have thought he was creating an impossible puzzle, but armed with MATLAB's matrix manipulation prowess, you've seen that elegant solutions exist. The key insights are recognizing the superdiagonal structure, handling forbidden squares through logical indexing rather than explicit loops, and carefully managing boundary conditions to ensure probability conservation. The transition matrix you've constructed doesn't just solve a Cody problem; it represents a complete probabilistic model of the game that could be used for further analysis, such as computing expected game lengths or steady-state probabilities.

The beauty of this approach lies not in clever tricks but in thinking about the problem at the right level of abstraction. Rather than considering each element individually, you've worked with entire diagonals, rows, and columns. Rather than writing conditional logic for every special case, you've used vectorized operations that handle all cases simultaneously. This is the essence of MATLAB mastery: letting the language's strengths work for you rather than against you.

As Vasilis Bellos demonstrated with the Bridges of Nedsburg , sometimes the most satisfying part of a Cody problem isn't just getting the tests to pass, but understanding the mathematical structure deeply enough to implement it elegantly. King Neduchadneddar would surely be impressed by your matrix manipulation skills, though he'd probably never admit it. Now go forth and construct those transition matrices with the confidence of a true Chief Royal Mage of Matrix Computations. The court awaits your solution.

Note: This article provides strategic insights and techniques for solving Problem 61067 without revealing the complete solution. The figures reference MATLAB Mobile script created by me that demonstrate key concepts. For the full Cody Contest 2025 experience and to test your implementation, visit the problem page and may your matrices always be stochastic.

Naomi Fernandes
Naomi Fernandes
Última actividad el 11 de Dic. de 2025 a las 13:54

Missed a session or want to revisit your favorites? Now’s your chance!
Explore 42 sessions packed with insights, including:
4 inspiring keynotes
22 Customer success stories
5 Partner innovations
11 MathWorks-led technical talks
Each session comes with video recordings and downloadable slides, so you can learn at your own pace.
Ned Gulley
Ned Gulley
Última actividad el 11 de Dic. de 2025 a las 8:54

The Ans Hack is a dubious way to shave a few points off your solution score. Instead of a standard answer like this
function y = times_two(x)
y = 2*x;
end
you would do this
function ans = times_two(x)
2*x;
end
The ans variable is automatically created when there is no left-hand side to an evaluated expression. But it makes for an ugly function. I don't think anyone actually defends it as a good practice. The question I would ask is: is it so offensive that it should be specifically disallowed by the rules? Or is it just one of many little hacks that you see in Cody, inelegant but tolerable in the context of the surrounding game?
Incidentally, I wrote about the Ans Hack long ago on the Community Blog. Dealing with user-unfriendly code is also one of the reasons we created the Head-to-Head voting feature. Some techniques are good for your score, and some are good for your code readability. You get to decide with you care about.
WANG Zi-Xiang
WANG Zi-Xiang
Última actividad el 11 de Dic. de 2025 a las 8:15

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!
Rik
Rik
Última actividad el 11 de Dic. de 2025 a las 4:55

There are multiple ways to create a graphical user interface (GUI) in Matlab. Which method is the best depends on multiple factors: the complexity of the project, to what extent it should be a long-term solution, on what releases your GUI should work, your available time, your skill level, and probably other factors I'm forgetting.
To keep the thread clear I'll attempt to provide a short outline a few ways in this question, and leave the details for the answers. (@anyone with editing privileges: feel free to update the section below if I missed something important and am slow in editing this question)
---------------------------------------------------------------------------------------------------
GUIDE
GUIDE is probably the first tool new users will encounter. It is very useful for quickly putting something together, but it is otherwise fairly limited. It requires maintaining (and distributing) both a .m and a .fig file. Note that the GUIDE environment will be removed in a future release. After GUIDE is removed, existing GUIDE apps will continue to run in Matlab but they will not be editable in GUIDE. If you're starting a new GUI, don't use GUIDE. If you're updating an existing GUIDE GUI, migrate it to AppDesigner. In R2021a the first step for this removal was taken: all templates except the blank template have been removed.
GUILT
Although I haven't had a detailed look myself, it seems a list like this is not complete without at least mentioning the GUI Layout Toolbox, which is available on the file exchange and offers a lot of customization options.
Programmatic GUIs
You can bypass GUIDE and use the normal figures and functions like uicontrol to build GUIs from code. This makes the design less visual, but more flexible for future additions.
App Designer
The official successor to GUIDE, AppDesigner is not based on functions, but works similar to a class. It uses uifigure and mostly uses graphical elements that are incompatible with 'normal' GUIs that are created with a figure (or .fig).
Walter Roberson
Walter Roberson
Última actividad el 11 de Dic. de 2025 a las 0:54

I can't believe someone put time into this ;-)
Luisa
Luisa
Última actividad el 10 de Dic. de 2025 a las 16:52

I believe that it is very useful and important to know when we have new comments of our own problems. Although I had chosen to receive notifications about my own problems, I only receive them when I am mentioned by @.
Is it possible to add a 'New comment' alert in front of each problem on the 'My Problems' page?
Rik
Rik
Última actividad el 9 de Dic. de 2025 a las 12:40

Similar to what has happened with the wishlist threads (#1 #2 #3 #4 #5), the "what frustrates you about MATLAB" thread has become very large. This makes navigation difficult and increases page load times.
So here is the follow-up page.
What should you post where?
Wishlist threads (#1 #2 #3 #4 #5): bugs and feature requests for Matlab Answers
Frustation threads (#1 #2): frustations about usage and capabilities of Matlab itself
Missing feature threads (#1 #2): features that you whish Matlab would have had
Next Gen threads (#1): features that would break compatibility with previous versions, but would be nice to have
@anyone posting a new thread when the last one gets too large (about 50 answers seems a reasonable limit per thread), please update this list in all last threads. (if you don't have editing privileges, just post a comment asking someone to do the edit)
David
David
Última actividad el 8 de Dic. de 2025 a las 15:44

I just learned you can access MATLAB Online from the following shortcut in your web browser: https://matlab.new
Our exportgraphics and copygraphics functions now offer direct and intuitive control over the size, padding, and aspect ratio of your exported figures.
  • Specify Output Size: Use the new Width, Height, and Units name-value pairs
  • Control Padding: Easily adjust the space around your axes using the Padding argument, or set it to to match the onscreen appearance.
  • Preserve Aspect Ratio: Use PreserveAspectRatio='on' to maintain the original plot proportions when specifying a fixed size.
  • SVG Export: The exportgraphics function now supports exporting to the SVG file format.
Check out the full article on the Graphics and App Building blog for examples and details: Advanced Control of Size and Layout of Exported Graphics

Acerca de Discussions

Discussions is a user-focused forum for the conversations that happen outside of any particular product or project.

Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!

Más áreas de la comunidad

MATLAB Answers

Pregunte y responda cuestiones sobre MATLAB y Simulink

File Exchange

Descargue o contribuya al código enviado por los usuarios

Cody

Resuelva grupos de problemas, aprenda MATLAB y gane insignias

Blogs

Contemple MATLAB y Simulink desde dentro

AI Chat Playground

Utilice IA para generar código inicial de MATLAB y obtener respuesta a sus preguntas.