欢迎参与!
"讨论" 版块是您认识同行、共同应对更大挑战并享受其中乐趣的地方。
更新的讨论
Another week, another fantastic collection of One-Button Games!
We saw some fantastic entries in our STEM Educationcategory:
- Roatis / BRASS & ENTROPY — The Maxwell Experiment
- VMM / How well can you read contour maps?
- JKMSMKJ /QUANTUM COLLAPSE!
- KARUPPASAMYPANDIYAN M / MATLAB MILLIONAIRE
Congratulations!
And our winners in the other categories are:
Originality:
Arcade:
Visualization:
A huge congratulations to all our Week 3 winners!
🏁 The Contest Is Almost Over. Get Your Games Played!
We’ll be recognizing the most-played games, so share your entries with friends, classmates, coworkers, family, and anyone else who might enjoy them.
And there’s something in it for the players too: community members who play and vote have opportunities to win MathWorks swag! 🎁
So spread the word, discover some new games, and vote for your favorites.
In our dynamics and kinematics course we simulated robots in low gravity, and I wondered what astronauts would do for fun after work. My answer is Moon Kick: tap once to lock the angle, tap again to set the power, and send the ball floating past a robot goalkeeper. Instead of storing pictures, the game calculates its sky, kick and goalkeeper with a little trigonometry.Play Moon-Kick
functions, used and its role
The contest needs only three handles. Everything else is a helper that takes the game state and returns the new state.
function g = game()
g.init=@ini; g.update=@upd; g.render=@rnd;
end
Every other part, like the goal check and the effects, is a small helper that takes the game state and returns the new state.
Two taps, two sine waves
Angle and power swing back and forth on sine waves, and your tap freezes the value.
s.ang = 8 + 70*(.5 + .5*sin(3.2*u));
v = 390*s.pw; s.vx = v*cosd(s.ang);
s.vy = v*sind(s.ang);
The Moon is just a smaller number
Lowering gravity in the step update makes every kick fly about six times farther.
s.vy = s.vy - 117*d;

A galaxy from polar coordinates
Each star's angle grows with its distance from the centre, which makes a spiral. Squashing the vertical part tilts it, and adding to the angle each frame rotate it .
r = 120*rand(n,1).^.7; a = r/18 + randn(n,1)*.25;
x = 400 + r.*cos(a); y = 430 + .45*r.*sin(a);

Moon-Bot, the goalkeeper
Moon-Bot glides up and down on a sine wave with a random phase. The shot is decided when the ball reaches the goal line. I work out the ball's height on that line, so even a fast ball can't skip past him
yy = y + (640-x)/(s.bx-x)*(s.by-y);

In few words for you to enjoy the game you have to master th power and angles as follow:
Tricks to play
- Lock the angle between 30° and 45°. This gives a long arc that lands inside the goal. Below 25° the ball needs almost full power, and above 50° it drops short or goes over the bar.
- Use about 70% power. At 35° the safe power is 63% to 80%, and full power sends the ball over the bar.
- Watch Moon-Bot's rhythm before you kick. He moves up and down about once per second. A flatter kick (30°) reaches him sooner, so he has less time to get in the way.
Final word
Behind every floating kick in Moon Kick, there is nothing more than a few trigonometric functions. A sine wave sweeps the aim, cosine and sine turn your tap into a flying ball, and polar coordinates draw a whole galaxy. This is what I love about MATLAB: a few simple functions can become a game.
So the next time you tap to lock the angle, remember that you are playing with trigonometry. Try the tricks above, then change a number and see what happens. I hope you discover how much fun it can be.
Thanks for reading, and enjoy the joy of trigonometry! 🌙⚽
From inverse perspective mapping to depth sorted sprite rendering and pixel level RGB composition
Introduction
As Thanksgiving gives way to the Christmas season, festive themes become a natural source of inspiration for game development. I wanted to capture that seasinal spirit through Santa's Christmas Flight, incorporating snowy landscapes, presents, and familiar holiday imagery. The project also provided an opportunity to explore pseudo 3D graphics in MATLAB. Its rendering pipeline combines perspective transformations, depth based object ordering, geometric mask rasterization, and direct RGB image manipulation to create an animated environment without relying on a conventional 3D graphics engine.
Game Demonstration
The playable game and accompanying animation illustrate the interaction between the rendering pipeline and the one button gameplay mechanics. The demonstration highlights the perpective based environment, animated sprites, and depth dependent object movement.
Animated Demonstration

Constructing the Rendering Pipeline
The rendering routine, rnd( ), orchestrates the transformation of the simulated environment into a two dimensional image. Its sequence integrates inverse perspective mapping, depth ordered object rendering, geometric mask construction, and RGB image composition. Each operation contributes to the spatial coherence and visual depth of the resulting scene.
So, with the rendering architecture established, let's look at a few techniques that make the implementation work. The following tips focus on the perspective calculations, depth ordering, and pixel level operations used to construct the game environment.
Tip 1-Establishing the Perspective Transformation
The perspective calculation begins with the depth dependent scaling factor in rnd( ):
zr=ch*f./((1:H-h0)');
xw=((1:W)-(W/2).*zr/f+cam;
The first expression assigns a depth value to each image row, while the second reconstructs horizontal coordinates relative to the camera displacement. Together, these calculations establish the coordinate mapping used to generate the perspective environment.
Tip 2-Projecting Objects at Different Depths
The rendering routine uses the following calculations to position individual objects:
u=f/z;
x=W/2+(q(2)-cam)*u;
yb=h0+(ch-q(3))*u;
The reciprocal depth factor u determines the projected scale, while x and yb establish the object's screen coordinates. As an object approaches the viwer, its projected dimensions increase, reinforcing the illusion of forward motion.
Tip 3-Rendering Objects in Back to Front Order
When several objects occupy different depths, their drawing order determines which objects appear infront of others. Your code addresses this by sorting the depth values before rendering:
[~,o]= sort(L(1,:); 'descend');
The first row of L contains the objects' depth values. Sorting these values in descending order places farther objects earlier in the rendering sequence, allowing nearer objects to becdrawn afterward. This is the Painter's algorithm: objects are composited from back to front so that foreground elements visually obscure background elements.
This small sorting operation is essential to the scene's depth perception. Without it, overlapping sprites could appear in the wrong visual order, weakening the perspective illusion.
Tip 4-Constructing Geometric Masks for Sprite Rendering
My dr( ) function uses normalized coordinates and a radial test to determine which pixels vpbelong to a rendered shape:
u=((x1:x2)-x)/w;v=((y1:y2)'-y)/h;r=u.^2+v.^2;
The variables u and v represent normalized horizontal and vertical distances from the shape's centre. Their squared sum, r, provides a convenient geometruc test for circular regions. This allows the renderer to construct shapes directly within the image array rather than relying on seperate graphics objects.
The technique is particularly useful for lightweight sprite rendering because the mask is evaluated only over the relevant pixel region.
Tip 5-Projecting Particles Using Depth Dependent Coirdinates
The same perspective principle used for scene objects also governs the placement of the environmental particles:
z=mod(s.fz0-s.dist*1.3,17)+.8;y=mod(s.fy-t*.9,6);
px=round(W/2+(s.fxx-cam).*f/z);py=round(h0+(ch-y).*f./z);
Here ,z determines each particle's simulated depth, while y supplies its vertical position. The expressions for px and py convert these coordinates into image locations using the focal parameter f and camera offset cam. The mid operations keep the particle coirdinates within repeating ranges as the scene advances.
What makes this implementation interesting is that the particles are not simply moved across the screen. Their apparent positions are recalculated through perspective projection, helping the environment convey continuous forward motion.
Concluding Remarks
Santa's Christmas Flight was an opportunity to bring together game development, mathematical modeling, and engineering principles within MATLAB. Although the game is designed around a simple one button interaction, its visual environment relies on concepts associated with computer graphics, including perspective projection, coordinate transformations, depth ordering, and geometric rasterization.
I particularly enjoyed exploring how a relatively compact rendering pipeline could reproduce visual effects commonly associated with three dimensional environments. The underlying mathematics also has broader engineering relevance: coordinate transformations and geometric projections are fundamental to robotics, machine vision, navigation, and simulation. Even the game's sense of forward movement depends on carefully manipulating spatial coordinates and their relationship to the camera.
From a physics perspective, the project illustrates how mathematical relationships can translate an abstract spatial model into a convincing visual experience. It reinforced an idea I find especially compelling: engineering principles need not remain confined to conventional technical applications. They can also become the foundation for interactive experiences that make mathematical and computationl concepts more approachable.
I hope these techniques encourage other MATLAB users to experiment with custom rendering, explore the mathematics behind visual effects, and discover new possibilities within the One Button Game format. I would also welcome comments, suggestions, and alternative approaches from the MATLAB community.
The MATLAB One-Button Game Mini Hack asks us to fit an entire game into 10,000 characters of MATLAB code. That becomes quite a challenge once we start adding detailed backgrounds, animated characters, and visual effects. But, as we've seen in previous Mini Hacks, embracing limitations can often spark ingenuity. And this year is no exception, as the contest's restrictions have brought out some rather creative programming, with participants finding ways to fit far more into their entries than the character limit might initially suggest.
In my earlier article on making games in MATLAB, I shared some of the graphics and programming ideas behind Arcade. This time, I would like to show how I created the artwork for my Mini Hack games and encoded it to fit inside the submitted code. We can draw a scene in MATLAB, reduce its images to the information needed to reconstruct them, and let the game recover the artwork from its own source. The same idea extends to the coordinates used to build 3D objects and their effects.
Saloon Brawl Knockout uses the characters from my earlier Western games for its fighters, background crowd, and bartender. Their separate body parts let them walk, duck, and throw punches while keeping the original pixel-art appearance:
The backgrounds and characters are prepared separately, so the same cast can appear in different locations. These are the four backgrounds from Trigger-Happy Mayhem, each drawn in MATLAB as a 150-by-200 image before the characters and props are added:
Together with the character parts and props, the original image arrays contain more than 1.5 million pixels. Sharing repeated artwork considerably reduces the data before compression. The encoded data is stored directly in game.m, alongside the code that reconstructs the images during initialization.
Drawing with palette indices
Let's start with a small piece of the artwork: the beer mug from Tipping Point. Its dark outline, amber fill, and foam fit into a 15-by-15 indexed image. Each array element stores a single integer that selects a color from a shared RGB palette, with 0 reserved for transparent pixels.
Filled polygons form the mug's body. The handle is added beside it, followed by the highlights and foam:
For example, these vertices define the dark outline of its body:
pixels = zeros(15, 15, 'uint8');
[x, y] = meshgrid(0:14);
outline = [1 3; 10 3; 10 12; 8 14; 3 14; 1 12];
pixels(inpolygon(x, y, outline(:,1), outline(:,2))) = 1;
The drawing coordinates run from 0 to 14, and meshgrid supplies the pixel centers. inpolygon selects the points inside or on the outline, so we can assign the value 1 to those pixels using logical indexing. A smaller polygon fills the body with amber. Rectangles add the visible part of the handle and the highlights, and further polygons form the foam.
The attached mugEncodingDemo.m contains the complete drawing, encoder, and decoder. Calling it with false returns the pixel array and RGB palette, which can be used to display the mug:
[pixels, palette] = mugEncodingDemo(false);
figure;
image(pixels, CDataMapping="direct", AlphaData=pixels ~= 0);
colormap(double(palette) / 255);
axis image off
For a uint8 indexed image, image maps each pixel value to the corresponding colormap row, following MATLAB's integer-image color mapping. AlphaData hides the pixels whose value is 0, while colormap assigns the palette after its RGB values have been scaled from the range 0–255 to 0–1.
The larger Western backgrounds use the same drawing operations. In Quickdraw, horizontal bands and alternating pixels form the sunset, polygons form the road and the hills, and rectangles build the storefronts, windows, signs, and boards. Loops are used to generate the repeated details. Once the scene is drawn, we can encode its pixel values into the game directly and omit the lengthy drawing routines.
Packing repeated pixels
Many neighboring pixels in the mug have the same value. Instead of writing each value separately, we can record the pixel value and length of each uninterrupted run. For example, in the fourth column highlighted below, the five consecutive pixels with value 9 become the pair 9, 5:
Tipping Point has 32 palette entries, so five bits are enough to represent a color index. Using another five bits for the run length lets us combine a color index from 0 to 31 with a length from 1 to 32:
token = colorIndex + 32 * (runLength - 1);
Dividing by 32 separates the two values: the remainder is the color index, and adding 1 to the integer quotient recovers the run length. Runs longer than 32 pixels are split into several tokens. To store those tokens compactly in the source file, we convert them to characters and recover their numeric codes when decoding:
values = double(pixels(:)');
starts = find([true, diff(values) ~= 0]);
runLengths = diff([starts, numel(values)+1]);
tokens = [];
for k = 1:numel(starts)
remaining = runLengths(k);
while remaining > 0
runLength = min(32, remaining);
tokens(end+1) = values(starts(k)) + 32 * (runLength-1);
remaining = remaining - runLength;
end
end
packed = char(19968 + tokens);
diff identifies changes between consecutive pixel values. Converting to double first preserves decreases as well as increases; unsigned integer subtraction would clip negative differences to 0. find returns the starting position of each run, and the differences between consecutive positions determine the run lengths.
Adding 19968 shifts the 1,024 possible token values into a range of Unicode character codes; char converts those codes to printable text. This range contains no quotation marks or control characters, so we can write the result between single quotes in game.m as a character vector literal. Each character represents one token, replacing the decimal digits and separators that would be needed to write that token as a number. This encoding takes place while preparing the artwork; the game starts with the resulting literal already in its source.
At initialization, double recovers the numeric character codes. Subtracting the offset restores the tokens, and mod and floor separate their colors and lengths. repelem expands the runs, and reshape reconstructs the original pixel array:
tokens = double(packed) - 19968;
colors = mod(tokens, 32);
lengths = floor(tokens / 32) + 1;
decoded = repelem(colors, lengths);
restored = uint8(reshape(decoded, 15, 15));
The mug's 225 pixels become 74 tokens, stored in 74 characters. The attached example verifies that decoding them reproduces every original pixel. Tipping Point combines the runs from all its images with their dimensions and palette, then compresses that collection further before embedding it in the game.
The double(packed) conversion above requires a character vector. A string scalar, written with double quotes, behaves differently: double("123") converts the text to the number 123. mxym discusses this distinction in their article on PULSE // PALS. The game also packs geometry, palette, and note-chart values into characters.
Pixel runs can also help when drawing an image. In their Ember Fox article, Cephas describes defining sprites as grids of # and . characters. Each horizontal run of # characters becomes one rectangle, reducing the number of shapes needed to draw the sprite. In addition, SunHuilin describes storing image data as pixel runs and each 7-by-7 effect pattern as seven integers in their Purrfect Fit article. The individual bits select the filled pixels, allowing the same drawing loop to produce hearts, paws, sparkles, and other effects.
Small numeric tables can also be packed into characters. Street Racer uses a 3-by-5 font, with each row represented by three bits. For the letter A, the five row values are 2, 5, 7, 5, 5, corresponding to 010, 101, 111, 101, 101. Five base-8 digits occupy 15 bits, so the whole glyph fits in one character:
rows = [2; 5; 7; 5; 5];
packed = char(256 + sum(rows .* 8.^(0:4)'));
rows = mod(floor((double(packed) - 256) ./ 8.^(0:4)'), 8);
pixels = logical(mod(floor(rows ./ [4 2 1]), 2));
The last line separates each row into its three bits, with 4, 2, and 1 corresponding to the left, middle, and right pixels. The same packing idea works for small coordinates and dimensions: Street Racer stores its car artwork as colored rectangle parameters, which the renderer uses to draw the intact and damaged cars.
Stefan Abendroth packs each car pixel in Drift Boss into four bits: three select one of eight palette colors, and one marks the pixel as opaque or transparent. Two pixels fit in each byte. Base64 represents those bytes as ASCII text in the source; during initialization, matlab.net.base64decode recovers the bytes before the color indices and opacity bits are separated.
Sharing character parts
Quickdraw's cowboy is assembled from separate layers for the body, trousers, head, hat, mustache, and arms. Most of these parts can remain in place while the arm moves through eight poses to draw the revolver. Keeping the layers separate also allows a well-timed shot to send the hat or mustache flying while the face underneath stays intact.
The original layers all use an 80-by-64 canvas, so the body parts align when overlaid. Much of each canvas is transparent. Before encoding it, the preparation code crops the layer to its nontransparent bounding box and stores the crop's position and size. During reconstruction, those values position the recovered pixels within the original canvas.
To animate the draw, the renderer selects the appropriate arm layer and overlays its nonzero pixels on the character. Transparent pixels leave the underlying image unchanged. Each pose is drawn beforehand from specified hand and elbow positions. Thick strokes form the sleeves and forearm, an ellipse forms the hand, and a small revolver image is rotated into position before the pose is encoded.
Trigger-Happy Mayhem shares parts across different characters as well. The preparation code groups crops that can be reconstructed from a common template and stores the color maps separately. The three rivals below share the same body template, with different maps supplying their jacket colors. Their faces, hats, arms, and lower bodies have separate template and color-map records. Rivals 1 and 3 also reuse identical faces, mustaches, legs, and trousers. The strips compare the maps used for the body:
The shared body template is a pixel array; the top strip lists its distinct values, using gray shades to distinguish them. Each rival's row shows the pixel values returned by its lookup table, colorMap, and the palette colors they select. Applying that table to every template pixel reconstructs the crop:
crop = reshape(colorMap(double(template(:)) + 1), size(template));
Each rival's color map preserves 0 for transparent pixels and maps the remaining template values to that rival's pixel values. For example, Rival 1's map converts both 2 and 3 to 52, while Rival 2's maps them to 55 and 52, and Rival 3's to 58 and 52. The stored crop offset places the result back in its original canvas.
The game reconstructs 207 image arrays from 64 templates and 85 color maps, including the four backgrounds, character layers, and props. A short record identifies each image's template and color map and specifies its original canvas size and crop position.
During preparation, the template pixels are compressed using their surroundings to estimate the probability of each possible value. Pixels are processed row by row, using their left, upper, upper-left, and upper-right neighbors as the context. Values assigned higher probabilities take less space to encode. As the decoder recovers each pixel, it updates the same probability model, allowing it to reproduce the original template and apply the appropriate color map.
Transforming pixel artwork
The separate body parts also let us change a character's pose during play. In Saloon Brawl Knockout, the sheriff bends at the waist to dodge a punch, while the rivals approach from the back of the room and rotate as they fall onto the table.
The game reconstructs the indexed artwork from shared templates and color maps, as in Trigger-Happy Mayhem. Each character layer is then converted into colored rectangles. The conversion groups vertically adjacent pixels of the same color into runs. Runs in neighboring columns are then merged when their colors and upper and lower edges match. Here's the conversion for one of the hat layers:
The hat's 375 colored pixels become 65 rectangles: about 83% fewer faces to transform and draw than using one rectangle per colored pixel. Each rectangle is defined by four corners and a palette index; transparent pixels need no geometry. The outlines mark the boundaries between the rectangles. The colors and silhouette remain unchanged.
To place a character, the renderer scales the vertices about a fixed origin and translates them to the character's position in the room. Increasing the scale makes the rival grow as he approaches:
The sheriff leans back at the waist and lowers his torso to dodge the punch. After the counterpunch, the rival's fall combines rotation with changes in position and scale. The face, hat, and mustache rotate with the body:
The renderer scales and rotates the rectangles directly, so that their corners are not restricted to the original pixel grid. The head, torso, and leg pieces are prepared during initialization and reused, while the pose calculations place the parts around the moving joints. Characters and moving props are drawn through one reusable patch object. The background remains a separate 150-by-200 indexed image, and the original palette supplies the colors for both.
Generating poses during initialization
We can also prepare a character's animation frames before play begins. Run & Gun generates its sprite images during initialization, building them from polygons, rectangles, disks, and connected limb segments. Changing the limb positions produces the running poses, while folding the body and rotating the assembled sprite produces the somersault:
The rifle is drawn with the body before rotation, so both turn together. The player frames are prepared once and retained; during play, the renderer selects the frame for the current action.
Preparing artwork during initialization is useful for scenery as well. Tharikaa Ramesh Kumar describes this in their Slingshot Home article, where a grid and a lighting expression generate the planet textures. Run & Gun prepares separate sky, scenery, and road arrays, which its renderer reuses to scroll the scenery at different speeds.
Copying repeated patterns
When encoding sprite images, repeated details provide another opportunity to save space. Repeated wheels, windows, or patches of shading can contain identical sequences of palette indices. We can store a reference to an earlier occurrence of a repeated sequence and have the decoder copy its values.
In Paperboy: Back on the Block, seven 24-by-24 sprites are joined into one array. Their 4,032 pixels are represented by 407 tokens. Each token either contains a pixel value or specifies a distance back into the decoded data and the number of values to copy.
This format reserves token values below 33 for individual pixels. For a copy token, the integer quotient after division by 33 is the distance, and adding 2 to the remainder recovers the copy length. The decoder starts with an empty array and appends either a pixel or a copied sequence for each token:
distance = floor(token / 33);
if distance == 0
decoded(end+1) = token;
else
copyLength = mod(token, 33) + 2;
indices = numel(decoded) - distance + 1 ...
+ mod(0:copyLength-1, distance);
decoded = [decoded, decoded(indices)];
end
The modulo operation allows the copied pattern to repeat when the requested length exceeds the distance. For example, when decoded ends with [4 7], a copy with distance 2 and length 6 appends [4 7 4 7 4 7]. During preparation, the encoder searches the preceding pixels for these matches and chooses between writing a pixel value and a copy token. The decoder follows the recorded choices; it doesn't need to repeat the search. Once all tokens have been expanded, reshape restores the original sprite array.
Generating character variations
colorbar generates its customers from a shared set of 34 shapes. Varying their proportions, colors, hairstyles, and accessories produces over 400 distinct appearances. The generator and its decoder use under 2,000 characters, including the encoded geometry and palette.
Ellipses form the faces, ears, eyes, and hands, while polygons form the clothing and other details. Each ellipse is stored as four values: its center coordinates and two radii. For example, the shared face ellipse can be encoded and reconstructed as follows:
parameters = [0, -82, 18, 23];
packed = char(19968 + 2*parameters);
parameters = (double(packed) - 19968)/2;
angles = (0:15)' * pi/8;
vertices = [parameters(1) + parameters(3)*cos(angles), ...
parameters(2) + parameters(4)*sin(angles)];
Multiplying by 2 allows half-unit values to be packed as integers. The decoder expands each four-character ellipse record into 16 vertices. For polygons, each pair of integer coordinates is combined into a single character, using the same remainder-and-quotient approach as the earlier color and run-length tokens. The shared palette supplies the base colors, and a short list of roles assigns skin, hair, clothing, or detail colors to each shape.
A customer's number selects the skin tone, hair and jacket colors, body width, and head proportions through modular arithmetic. For example, mod(identity,6) cycles through six hairstyles, while mod(identity,5) selects one of five skin tones. The number also determines which optional parts appear, including glasses, facial hair, ties, and earrings. These choices are linked by the same number, producing a repeating sequence of appearances. The game retains the resulting geometry until the customer's identity changes; blinking, service reactions, and movement are applied to those vertices during play.
The attached colorbarCharacterDemo.m expands those compact functions for readability and adds a gallery for browsing all 14 sheets of 30 customers. The numbers match the identities used by the game. Run colorbarCharacterDemo() to open it, or return the complete collection without opening a window:
customers = colorbarCharacterDemo(false);
Calling colorbarCharacterDemo(ExportFolder="customers") also saves the 14 numbered sheets as PNG images. The example includes the shared data and helpers, so it can be used independently of the game.
Encoding glass geometry
Shatterglass uses five flat profiles and eight glass volumes. The renderer assigns their face and outline colors from the game's palette:
The vertex coordinates are multiplied by 1000 and rounded to integers. Adding an offset of 20000 shifts these integers into a range of character codes, similarly to the mug's run tokens. The indices used to draw the exterior edges are packed into characters as well. These short vectors describe the original shapes; the game calculates their changing positions and orientations in real time.
There’s more to store than just the geometry. The palette, fracture weights, graphics settings, and other fixed game data are grouped into a collection of constants. To compress that collection together, we first need to turn its differently sized arrays and text values into a single sequence. MATLAB's jsonencode writes them as structured JSON text. The compressor works with byte values from 0 to 255, so unicode2native converts the text to bytes using the UTF-8 encoding. The diagram below illustrates the encoding and decoding process:
The attached glassEncodingDemo.m includes the original packed data and all the functions needed to decode it and draw the volumes. It also reproduces the encoding, using the following preparation code:
prepared = prepareGlassArrays(constants);
json = jsonencode(prepared, ConvertInfAndNaN=false);
bytes = unicode2native(json, 'UTF-8');
packed = encodeAssetBytes(bytes);
byteCount = numel(bytes);
prepareGlassArrays preserves array information that JSON would otherwise lose. For example, the game's empty 0-by-9 and 0-by-17 arrays would both become []; recording their dimensions lets the decoder distinguish and rebuild them. ConvertInfAndNaN=false also retains the nonfinite values used by the game in MATLAB's JSON representation. The original byte count is saved with the packed data so the decoder knows how many bytes to recover.
The custom encodeAssetBytes helper compresses those bytes using adaptive range coding. It estimates probabilities for the next byte from counts of values previously seen after contexts of up to four bytes. Those estimates divide a numeric interval among the possible next values, allocating larger portions to more probable values. Each input byte selects its portion and narrows the interval. The decoder follows the same divisions to recover the bytes, updating its counts in the same order as the encoder. Both build the model as they go, so its frequency table can be omitted from the stored data.
We still need to include the compressed output in the MATLAB source. The compressor produces 20-bit integers, which are larger than the mug's 10-bit tokens. MATLAB stores a char array as 16-bit elements using UTF-16; some Unicode characters are represented by a pair of these elements. The helper splits each compressed integer into two 10-bit parts and places them in such a UTF-16 surrogate pair. The 3,413 input bytes become 633 packed integers, occupying 1,266 elements of the character vector written into game.m.
At initialization, the following sequence reverses the process:
bytes = decodeAssetBytes(packed, byteCount);
json = native2unicode(bytes, 'UTF-8');
constants = restoreGlassArrays(jsondecode(json));
decodeAssetBytes unpacks the characters and recovers the byte sequence. native2unicode interprets those bytes as UTF-8 to recover the text, and jsondecode turns it back into MATLAB values. restoreGlassArrays reconstructs arrays from their recorded dimensions and converts the remaining column vectors to rows.
The constants are decoded once, during initialization. Running glassEncodingDemo() displays the reconstructed volumes, and glassEncodingDemo(false) returns the decoded data without opening the figure.
The recovered constants include the packed coordinate and edge-index vectors for each volume. We can now turn these back into the points, triangular faces, and outline used to draw the shape:
vertices = reshape(double(packedCoordinates) - 20000, 3, [])' / 1000;
faces = convhull(vertices);
edgeIndices = double(packedEdges) - 20000;
outlineVertices = [vertices; NaN(1,3)];
edges = outlineVertices(edgeIndices, :);
Subtracting 20000 recovers the stored integers; dividing by 1000 restores their coordinate scale. Each row of vertices contains one point's x, y, and z coordinates. convhull returns triangles covering the boundary of the convex solid, which can be passed to patch. For the octahedron, this produces its eight outer triangular faces, with no surface between the upper and lower halves.
The exterior edge path is stored separately because the triangulation also contains diagonals across flat faces. Drawing only the selected edges keeps those diagonals out of the glass outline. The appended NaN row provides breaks between the separate segments when the outline is drawn with line.
Deriving the shards and reflections
The triangular faces also provide the geometry for the shattering effect. A common set of weights selects each face's corners, edge midpoints, and an interior point. Matrix multiplication combines these weights with the coordinates of the face's three vertices to divide it into six smaller triangles. The same subdivision works for every volume. The animation below uses the game's collision and rendering functions to demonstrate the shattering effect and reflections:
The cube has 12 surface triangles and produces 72 shards. Each shard is assigned an initial velocity; its position and rotation are calculated from the time since impact. The shards fall under gravity, then bounce and slow down as they settle flat on the floor.
The reflection uses a second copy of the displayed geometry with its vertical coordinate reversed. For a floor at z = 0, the operation is:
reflectedVertices = vertices .* [1, 1, -1];
The wall reflections reverse the x coordinates about each wall's position, while the ceiling reflection reverses the z coordinates about its height. Intact glass, moving shards, and balls are mirrored from their current geometry. The renderer reduces the opacity of the reflected glass and darkens the ball reflections. The orientations of the glass faces also determine their shading and transparency as the fragments turn. Shatterglass creates its graphics objects once and reuses them, changing their vertices, colors, and transparency as the objects move or break.
Validating the game
The encoder can remain in the development files, but the submitted game needs to include everything required to reconstruct its graphics. That includes the palettes, dimensions, lookup tables, and decoder. A small font or a few rectangles may need only a short unpacking expression. A larger collection can share a more elaborate decoder across many assets, and may also benefit from retaining drawing routines for repeated shapes or poses.
For Shatterglass, an equivalent version using direct MATLAB routines and ordinary numeric arrays uses 16,399 counted characters. Encoding the game brings this down to 10,000:
The counts cover the complete game, including the code needed to decode and use the stored values. Both versions retain the same gameplay, graphics, shattering, and reflections.
The preparation code checks each representation by decoding its output and comparing it with the source arrays. For example, isequal checks that every palette index in the reconstructed mug matches the original. For the glass, the comparison uses the rounded coordinates. The mug and glass demos include these reconstruction checks. All three attachments contain their own data and helpers, so they can run independently of the games.
When validating the character count, use the contest tools on the game.m file. The validator also parses and reformats the code before counting it, excluding comments. Mohammad Aryayi discusses this in their account of reducing Stack OverDad, which also describes packing the coordinates of rectangles, ellipses, and polygons into character codes. Save the file as UTF-8 in order to preserve the packed character literals, then run minihackContest.validate before submitting the game.
I hope these examples give you a few useful ways to make room for more of your own graphics. If you try a different representation or find a particularly effective way to pack your artwork, I would be interested to see it! I look forward to seeing many more amazing games from everyone taking part in the Mini Hack!
A proton or carbon-ion beam deposits most of its dose at the very end of its path, in the Bragg peak, and almost nothing beyond it. That is the whole promise of particle therapy: cover the tumour, stop right after it, spare the organ behind. It is also its weak point. The beam stops where the tissue says it stops, and if the range is off by a few millimetres you either leave part of the tumour cold or overshoot into the brainstem.
Choosing where the beam stops felt like a natural fit for one button. After *X-Ray Guided* (coronary stenting) and *Y-90: Target the Liver Tumour* (radioembolization), this is my third entry. I am a medical physicist, and this time I wanted to play with something every particle therapy physicist worries about: range, and the choice of the particle.
How to play
Each patient is an axial CT slice, brain or lung, with the tumour in red and the organs at risk in colour. The beam always comes from the left.
- Choose the beam: PROTONS and CARBON IONS are highlighted in turn, tap to pick one. The depth-dose panel on the right previews both along the tumour. The yellow line on the patient card is the clue: a hypoxic tumour, a child, the heart behind the tumour, a long path through lung.
- Fire: the tumour is treated band by band. A cyan marker shows where the beam will stop (the distal edge, R80). It sweeps back and forth at constant *water-equivalent* speed, so it races through lung and crawls through bone. Tap to fire the band.
- Report: tumour control or recurrence, cold spots in blue, organ doses in green or red on the card.
The catch is the range uncertainty. The tumour is judged with the range 3 % short, the organs at risk with the range 3 % long. Stopping exactly on the tumour edge is not enough: aim a little past it, but not so far that the organ behind takes the dose. A recurrence or any toxicity costs a life; three lives per shift, and the marker gets faster patient after patient.

Protons or carbon?
Every case has a reason to prefer one particle, taken from the real arguments (simplified):
- Hypoxic tumour: protons cannot control it, carbon ions can (higher LET, less dependence on oxygen).
- Long path through lung: the proton entrance plateau is higher, so the lung in front of the tumour gets more dose. Carbon wins.
- Child: the carbon RBE is less certain in growing tissue, so the game adds a larger safety margin on organ doses, and the low-dose fragmentation tail beyond the peak reaches the hippocampus behind the tumour. Protons win.
- Heart behind the tumour: the same tail exceeds a strict mean-heart-dose limit. Protons win.
- Meningioma: either works, just aim well.
Real vs. playable
What I kept real
- Range in water-equivalent depth: each tissue has its own stopping power, so the same energy goes further in lung and less far in bone.
- Spread-out Bragg peak (SOBP) covering the tumour thickness, with an entrance plateau that is higher for protons and a distal fall-off that is wider for protons and sharp for carbon.
- Dose in Gy(RBE): RBE 1.1 for protons, variable for carbon (about 1.3 in the plateau, 2-3 in the SOBP), plus a fragmentation tail beyond the peak.
- Robust evaluation against ±3 % range uncertainty, as in robust optimisation: worst case for the target, worst case for the organs.
- Organ constraints in the clinical form (Dmax, mean, Vx, Dx).
What I changed for playability
- One beam, one 2D slice, analytic depth-dose curves instead of a dose engine.
- Synthetic anatomy made of ellipses.
- Some limits are game values, tuned so that the choice of the particle matters (the mean heart dose and hippocampus limits, for example). Hypoxia is all or nothing.
- The beam energy is not chosen from a list:** the marker sweeps and you tap.
Three things I learned
- A "choice" is only a choice if the game can prove it.** My first versions had cases where both particles worked, or neither did, for reasons the player could not see. In the end I wrote a bot that plays every scenario with both particles and a perfect aim, 50 patients each, and kept tuning anatomy and limits until the right particle succeeded almost always and the wrong one almost never. The table it prints became my design document.
- Uncertainty makes a timing game a margin game.** Without the ±3 % rule the best tap is "exactly on the edge". With it, there is a window: too short and the tumour is cold in the short scenario, too long and the organ behind is hot in the long one. The window is wider for carbon's sharp edge than for the proton fall-off, which is exactly the physics.
- Characters: the validator reformats your code.** Spaces around operators, `( ` and ` )` in calls, and four spaces per indentation level all count. Flattening nested `if`s saved more than any variable renaming. Two other tricks did a lot:
% anatomy as a string: tissue digit, then cx cy a b angle, one char each
for q = reshape(A,6,[])
v = (q'-64)/4;
I(E(s,[o+v(2:3) v(4:6)])) = q(1)-48;
end
% rotated ellipse with complex numbers (s.Z = X + iY)
z = (s.Z-v(1)-1i*v(2))*exp(-1i*v(5));
e = (real(z)/v(3)).^2+(imag(z)/v(4)).^2 < 1;
How many patients do you get through? And if you work in particle therapy: what did I oversimplify?
My initial idea was one game covering a satellite's full attitude-control operation: stop the spin after launch, then point at a target. It didn't fit in 10,000 characters of MATLAB. Real spacecrafts don't do it all in one go either, so I split it into two games:
Keywords:
AOCS (Attitude and Orbit Control System) is the part of a spacecraft that knows which way it's facing and turns it where it needs to point.
Detumbling is the first job after a satellite separates from its rocket. It's usually spinning, so the AOCS has to bring that rotation close to zero before anything else can happen.
Pointing comes next: aiming a camera, antenna or laser at a target and keeping it there while the satellite moves along its orbit.
Conservation of angular momentum links detumbling and pointing: with no external torque, total spin can only move between parts, so spinning a reaction wheel one way turns the satellite the other way.
H = I_body·ω_body + I_wheel·ω_wheel = constant
Why two games? Different phases, different needs
A spacecraft's needs change over a mission. Right after launch it has to stop tumbling; later it has to point accurately at targets, and each phase calls for a different control approach. So I split the two: each game covers one phase, simplified with one wheel on one axis.
Phase 1: Single-Wheel Detumble

Your satellite is tumbling at 10–19°/s. Hold the button to spin the wheel and absorb the spin. Get the rate below 0.5°/s and hold it there for 2 seconds.
Phase 2: Single-Wheel Target Tracking

A ground station moves beneath your orbit. Turn the satellite until the camera's boresight is on it, then keep it within 3° for 3 seconds.
How to play both games
- Hold = wheel motor on. Release = off.
- The direction alternates with every press. The arrow on the wheel shows which way it spins.
- Watch the BODY + WHEEL = TOTAL H chart: as one goes up the other goes down. That's conservation of angular momentum!
Which did you find harder, stopping the spin or holding the target? 🛰️
This Week's Quiz
100 responses
A MATLAB Implementation of the Biot-Savart Law, Field-Uniformity Analysis, and Boris Integration
Introduction
Developing HELMHOLTZ HERO was far more challenging than I initially expected. I spent many long hours working through the physics, refining the MATLAB implementation, troubleshooting numerical errors, and trying to make several independent components work together without compromising the underlying science. One of the biggest challenges was translating the Biot-Savart law into a numerical calculation that could represent the magnetic field generated by two interacting circular coils. Getting the 96 segment integration, field superposition, spatial interpolation, RMS uniformity calculation, and Boris particle integrator to work together required patience and a fair amount of experimentation.
I am sharing some of the techniques and lessons I learned during that process because getting a physics-based STEM project to work involves considerably more than writing code that runs. The mathematical model must be consistent with the physical system, numerical approximations must be understood, and the visual output must accurately reflect the calculations behind it. The tips that follow focus on the approaches that helped me develop and troubleshoot this particular simulation, including some of the mistakes and technical details that I would pay closer attention to if starting the project again.
HELMHOLTZ HERO: A Numerical Exploration of Electromagnetism
Before discussing the technical lessons behind the project, I invite you to explore HELMHOLTZ HERO, my MATLAB One Button Game entry. It is an interactive physics simulation that brings magnetostatics and charged-particle dynamics into a hands on learning experience. Through a simple one-button control scheme, players explore magnetic-field uniformity, adjust physical parameters, and observe how those changes influence particle motion.
The animated demonstration below illustrates the simulation in action, showing how the magnetic-field configuration changes.

The following tips describe some of the numerical methods, MATLAB programming techniques, and practical problem-solving approaches I used during development.
Tip 1: Validate the Numerical Field Calculation Before Visualizing it
One of the most important lessons I learned while developing HELMHOLTZ HERO was to validate the numerical calculation before refining the visual presentation. A field map may look physically plausible, but its appearence alone does not establish numerical accuracy. In my implementation, I used the Biot-Savart law to calculate the magnetic field components at each observation point. The circular integration is approximated using 96 angular midpoint samples, defined directky in the bf() function:
c=cos(((1:96)-0.5)*2*pi/96);
For each current loop, the function calculates the axial displacement zr, applies the relative current cur, and evaluates the geometric denominator D:
zr=z-(k-1.5)*d;
cur=1+(r-1)*(k-1);
D=(x.^2+1+zr.^2-2*x*c).^1.5;
The radial and axial field components are then accumulated using the angular samples:
bx=bx+cur*sum(c.*zr./D,2)/96;
bz+cur*sum((1-x.*c)./D,2)/96;
A useful verification technique is to compare the numerical result with a known analytical solution. For the ideal Helmholtz configuration, the normalized magnetic field at the midpoint is:
BH_over_B0=2*(4/5)^(3/2);
The expected value is approximately 1.4311. This provides a reference for checking the numerical implementation before relying on its field visualization and uniformity calculations.
Practical takeaway: Validate the numerical physics against an analytical benchmark before trusting the visual output.
Tip 2: Create Graphics Objects Once and Update Them During Animation
One programming decision that made HELMHOLTZ HERO more manageable was seperating graphics intialization from frame by frame updates. Instead of repeatedly creating new plots, surfaces, and graphical objects during gameplay, I created the graphics handles in initState(ax) and updated their properties through renderFrame. This seperation is particularly useful in an animated MATLAB application, where graphics are refreshed reoeatedly as the simulation progresses.
Keeping the initialization and rendering responsibilities seperate has two practical advantages: it avoids unnecessary graphics object creation and makes the rendering routine easier to maintain. It also helps prevent the accumulation of obsolete graphical objects during animation.
Practical takeaway: Intialize your graphics once, retain their handles, and update the existing objects rather than recreating the entire visualization every frame.
Tip 3: Implement a Boris Style Magnetic Rotation for Particle Motion
A particularly interesting part of HELMHOLTZ HERO is the numerical integration of the particle trajectory. I used a Boris style rotation to update the particle velocity in response to themsgnetic field calculated at its current position. The method relies on vector cross products to produce the velocity rotation rather than using a straightforward component by component update.
The particle starts with the following initial position and velocity:
q=[0 0 -1,8];
v=[0.5 0 1];
The integration uses 12 substeps per frame. At each substep, rho gives the particle's distance from the symmetry axis, and bf() calculates the local radial and axial magnetic field components using the current coil parameters:
rho=hypot(q(1),q(2));
[br,bz]=bf(rho,q(3),s.d,s.r);
The radial field component is then resolved along the particle's Cartesian coordinates. The small denominator safeguard prevents division by zero when the particle approaches the symmetry axis. The vectors tv and sv determine the magnetic rotation:
f=br/max(rho,1e-9);
tv=0.02*[f*q(1) f*q(2) bz];
sv=2*tv/(1+tv*tv');
The velocity update applies the cross product rotation, after which the particle position is advanced:
v=v+cross(v+cross(v,tv),sv);
q=q+0.01*v;
Repeating these operations over the 12 substeps produces the trajectory shown in the game. Notice that the implementation uses fixed increments of 0.02 and 0.01; it does not currently scale these values with the frame time argument dt. The method also models magnetic rotation only, without an electric field contribution.
Practical takeaway: Evaluate the magnetic field at the particle's current position, perform the velocity rotation, and then advance the position. Keeping these operations in a clear sequence makes particle integration easier to inspect and troubleshoot.
Tip 4: Quantify Magnetic Field Uniformity with RMS Error
A key part of HELMHOLTZ HERO is measuring how uniformly the magnetic field is distributed around the center of the simulation. Instead of relying only on the visial field map, I use the magnetic field magnitude at the center as a reference and calculate the relative deviation across the grid.
The following lines from field(s) calculate the field magnitude, establish the central reference value, and determine the relative deviation:
b=hypot(bx,bz);
bc=b(13,20);
e=b/bc-1;
The code then selects a seven by seven region around the center of the grid and calculates its root mean square (RMS) deviation:
w=e(10:16,17:23);
s.rms=sqrt(mean(w(:).^2));
Using w(:) converts the selected region into a column of values for the calculation. Squaring the devistions prevents positive and negative differences from canceling each other. The square root then returns the RMS result to the scale of the original relative deviations.
In this implementation, the RMS value measures variations in magnetic field magnitude within the selected region; it does not independently measure the uniformity of each field component.
Practical takeaway: Establish a reference field value, select a consistent measurement region, and use RMS error to quantify local field uniformity. This provides a numerical basis for comparing simulation results rather than relying on visual inspection alone.
Tip 5: Use MATLAB Graphics Handles to Animate a Physics Simulation
A useful technique in HELMHOLTZ HERO is to create the graphics objects once and update their properties as the simulation changes. In initState(ax), I create the field map image and magnetic firld direction arrows, storing their handles in s.g.im and s.q.q. The field map is created using the calculated RGB data in s.E:
s.g.im=image(ax,[50 544],[391,79],s.E,o{{:});
s.q.q=quiver(ax,cx+s.ZZ(1:4:25,2:4:38)*...
S,cy-s.XX(1:4:25,2:4:38)*S,s.U,s.V,0,...
'Color',[1 1 1],'LineWidth',1,o{:});
In renderFrame, I update these existing graphics objects using their stored handles. The CData property refreshes the field map colors, while UData and VData update the arrow components:
h.im.CData=s.E;
h.q.UData=s.U;
h.q.Vdata=s.V;
The same approach updates the particle trail and its moving marker. The trail uses the coordinate arrays s,tx and s.ty, while the particle marker follows the latest recorded position:
h.tr.XData=s.tx;
h.tr.YData=s.ty;
h.hd.XData=s.tx(max(s.i,1));
h.hd.YData=s.ty(max(s.i,1));
This seperation between graphics initialization and rendering keeps the visualization synchronized with the changing magnetic field and particle trajectory without repeatedly creating new graphics objects.
Practical takeaway: Store graphics handles when creating plots, images, and vector fields. Update their data properties during animation to keep MATLAB visualizations efficient and easier to maintain.
Final Thoughts: Turning Magnetostatics into an Interactive Experience
Developing HELMHOLTZ HERO brought together several areas of computational physics and MATLAB programming in a single interactive project. The implementation combines a numerical Biot-Savart field calculation, magnetic field uniformity analysis, Boris style particle integration, and graphics updates to create a playable exploration of magnetostatics.
The one button design makes the experience accessible while preserving meaningful physics concepts. Players adjust the seperation between the simulated circular current loops and their relative current ratio, observe how these parameters affect magnetic field uniformity, and see how a charged probe responds to the resulting magnetic field.
My goal was to make the underlying physics more approachable through experimentation rather than passive observation. I hope HELMHOLTZ HERO encourages other MATLAB users to explore computational physics, experiment with numerical methods, and develop interactive learning experiences of their own.
Thankyou for exploring HELMHOLTZ HERO!
Update: I’ve released waitForFigureLayout as a standalone utility to make it easier to use in your own apps. You can download the packaged version from MATLAB Central File Exchange.
I wanted to read a grid child’s Position immediately after resizing its parent. Sometimes drawnow returned while the child still had its old size. A second read, with no further changes to the figure, gave a different rectangle.
A MATLAB uifigure has a browser-based client that computes grid layout and reports the resulting positions back to MATLAB. So when can MATLAB code read the updated values? In the layouts I tested, a wait inside that client gave me the same Position values as a later read. The wait starts with 220 ms without a container resize notification, then lets the client finish the layout work it has queued.
This post is an abridged English adaptation of my own article on Qiita (in Japanese). I used AI assistance to prepare the English write-up and reproduction files.
Caution: This trick relies on undocumented, private MATLAB internals. It was verified only by testing on Windows and may stop working in any release.
Why a position can change after drawnow
The uigridlayout documentation mentions that a child’s Position may lag when it is added to a grid. I saw the same kind of lag when resizing an existing grid. MATLAB updates the component properties as position change events arrive from the uifigure client. A read can occur while the client still has another relayout pending.
In the Windows releases I inspected (R2023a through R2026b), the Grid Layout controller used a 200 ms Lodash throttle for parent resize events, with both leading and trailing calls enabled. The first resize can run immediately. If another comes in during that interval, the trailing call can run on a timer, using the latest resize. If the grid contains another resizable container, that relayout can trigger another resize further down the tree.
The internal ViewModel method stabilize() waits for registered asynchronous work. The trailing timer hasn’t registered a relayout yet, so the ViewModel can report that its current work is done while the timer is still pending. A single requestAnimationFrame can also run before that timer fires.
How I waited for updated positions
Run JavaScript in the uifigure client
Reaching that window through the figure's hidden Controller follows the approach Yair Altman described in Customizing uifigures on Undocumented MATLAB. In the releases I tested, the window is on the controller's PlatformHost rather than its Container. The code registers a listener on the figure's ViewModel, then calls executeJS on that window. The JavaScript sends a completion event through the ViewModel after waiting for the layout. These steps use private APIs and require a figure whose host exposes a CEF window.
On Windows, use an ordinary uifigure from R2023a through R2024b. To use the same code in the desktop from R2025a through R2026b, create a separate figure window with the undocumented matlab.ui.internal.uifigureIsolated. Use fig = matlab.ui.internal.uifigureIsolated; in place of fig = uifigure; when creating the figure.
Wait for the grid’s resize work
- Wrap emitContainerResizeControllerEvent on the figure’s container controllers. Record the time of the most recent resize notification and keep that timestamp across waits. When installing a new hook, start the quiet period afresh because earlier notifications may have been missed.
- Wait for 220 ms without another notification. That is the Grid Layout controller’s 200 ms throttle interval plus a 20 ms margin. Each resize restarts the quiet period, so nested relayouts have time to schedule their own work. Give up after three seconds of continued activity.
- Await stabilize() when it exists, then wait one animation frame. In R2023a and R2023b, the grid relayout itself was scheduled as an animation-frame callback. In R2024a and later, the relayout was registered with the ViewModel.
- Send the completion event through the figure’s ViewModel so that it follows position notifications already dispatched on that channel. On receipt, read the MATLAB properties.
The 220 ms interval is derived from the throttle in the implementation I inspected. Both the throttle interval and the private APIs can change between releases.
Validation
I used a panel containing a two-row grid with a 'fit' label above a tab group. The second tab contained a nested grid and label. After the initial layout had settled, I measured a second wait and compared the outer label’s and tab group’s Position and the nested label’s getpixelposition(...,true). I took the first reading after the wait and a drawnow, and the second 0.5 seconds later.
In interactive MATLAB desktop sessions on Windows, I ran six trials per scenario in each release from R2023a through R2026b. All three rectangles agreed in all 192 trials.
The per-release median waits ranged from 241 to 249 ms after resizing the panel, enlarging the fit-row label, switching tabs, and enlarging the nested label. They ranged from 233 to 246 ms after only the panel resize and label enlargement, and from 296 to 375 ms after two panel resizes 50 ms apart. With no change, the wait took 8 to 12 ms.
The attached layoutWaitDemo.zip contains a smaller reproduction fixture, a single grid whose parent is resized twice within the throttle interval, and the same waitForFigureLayout.m and waitForFigureLayout.js shown below. To compare drawnow alone with the browser wait, extract the ZIP and run this command from the extracted folder.
matlab -batch "layoutWaitDemo(false, 8); layoutWaitDemo(true, 8)"
In this smaller fixture on Windows R2023a, R2024b, and R2026b, each release showed a position change after the first read in 8/8 baseline runs and 0/8 runs with the browser wait. The median extra waits were 362, 375, and 377 ms, respectively.
Using the wait in your own code
Save the two blocks below as waitForFigureLayout.m and waitForFigureLayout.js in the same folder and put that folder on the MATLAB path. Call the function once before editing the layout to install the resize hooks. After making your changes, call it again before reading Position. Keep the figure visible while waiting for the animation frame.
fig = uifigure;
panel = uipanel(fig, "AutoResizeChildren", "off", "Position", [20 20 300 250]);
grid = uigridlayout(panel, [1 1]);
child = uilabel(grid, "Text", "Grid child");
drawnow
waitForFigureLayout(fig); % Install hooks before the first layout change.
panel.Position(3:4) = [400 300];
drawnow
waitForFigureLayout(fig); % Wait for the queued resize work and its reply.
drawnow
position = child.Position
MATLAB file: waitForFigureLayout.m
function waitForFigureLayout(fig)
% waitForFigureLayout Dispatch the browser wait and receive its result on the figure ViewModel.
arguments (Input)
fig (1, 1) matlab.ui.Figure
end
% Find the browser window that hosts the figure.
% struct() reads every hidden property, so besides MATLAB:structOnObject it can
% emit unrelated deprecation warnings (JavaFrame, GraphicsSmoothing, ...).
% Silence all warnings only for these three calls.
warningState = warning("off", "all");
warningCleanup = onCleanup(@() warning(warningState));
figureData = struct(fig);
controller = struct(figureData.Controller);
host = struct(controller.PlatformHost);
clear warningCleanup
assert(isfield(host, "CEF") && ~isempty(host.CEF), ...
"This figure has no CEF window. Use uifigure through R2024b. " + ...
"In R2025a or later, create the figure with matlab.ui.internal.uifigureIsolated.");
viewModel = controller.ViewModel;
% Use a unique completion event for this request and subscribe before dispatch.
requestId = erase(string(java.util.UUID.randomUUID()), "-");
eventName = "FigureLayoutWaitCompleted_" + requestId;
reply = [];
listener = viewModel.addEventListener(char(eventName), @receive);
listenerCleanup = onCleanup(@() delete(listener));
configuration = struct("figureId", string(viewModel.getId()), ...
"channel", string(matlab.ui.internal.FigureServices.getUniqueChannelId(fig)), ...
"eventName", eventName);
source = fileread(fullfile(fileparts(mfilename("fullpath")), "waitForFigureLayout.js"));
script = replace(string(source), "__LAYOUT_WAIT_CONFIGURATION__", string(jsonencode(configuration)));
host.CEF.executeJS(char(script), 10);
% Yield to MATLAB callbacks and bound the wait for a missing browser reply.
clock = tic;
while isempty(reply) && toc(clock) < 8
pause(0.01);
end
assert(~isempty(reply), "Timed out waiting for the figure ViewModel reply.");
if isfield(reply, "error")
error("Browser layout wait failed: %s", string(reply.error));
end
clear listenerCleanup
function receive(~, event)
% receive Store the payload for this request's completion event.
reply = event.data;
end
end
JavaScript file: waitForFigureLayout.js
(config => {
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
require(["viewmodel/impl/ViewModelManagerFactory", "MW/componentframework/ControllerService"],
async (factory, service) => {
const managers = Object.values(factory._viewModelManagerCache)
.filter(manager => manager.hasById(config.figureId));
if (managers.length !== 1) {
throw new Error("Expected one ViewModel manager for this figure.");
}
const manager = managers[0];
const viewModel = manager.getById(config.figureId);
const send = result => viewModel.dispatchEvent(config.eventName, viewModel,
result);
try {
// Keep resize timestamps across calls in this demo figure.
const resize = viewModel.figureLayoutWaitResize ??= {
last: performance.now(), hooked: new WeakSet()
};
const cache = service.getInstance(config.channel)._controllerCache;
const controllers = cache instanceof Map ? [...cache.values()] : Object.values(cache);
let watched = 0;
for (const controller of controllers) {
const original = controller?.emitContainerResizeControllerEvent;
if (typeof original !== "function") continue;
watched++;
if (resize.hooked.has(controller)) continue;
controller.emitContainerResizeControllerEvent = function (...args) {
resize.last = performance.now();
return original.apply(this, args);
};
resize.hooked.add(controller);
resize.last = performance.now();
}
if (watched === 0) throw new Error("No resize emitters found.");
// Let pending browser work run, then wait out the trailing resize timer.
document.body.getBoundingClientRect();
await delay(0);
const started = performance.now();
while (performance.now() - resize.last < 220) {
if (performance.now() - started >= 3000) {
throw new Error("Resize activity did not settle within 3 seconds.");
}
await delay(10);
}
// Drain registered layout work where supported, then wait one frame.
const root = manager.getRoot();
if (typeof root.stabilize === "function") await root.stabilize();
await new Promise(resolve => requestAnimationFrame(resolve));
send({ completed: true });
} catch (error) {
send({ error: String(error) });
}
});
return config.eventName;
})(__LAYOUT_WAIT_CONFIGURATION__)
I'd rather not believe this far too hacky way is the only thing to do. Has anyone found a supported way to wait until a grid layout's updated positions are available on the MATLAB side? I'd also be interested in results from other platforms or nested layouts.
Hope you remember the little working games when you were a kid :D
I made a little café game called A Little More using MATLAB and Codex, where you make drinks for different customers using just the Space bar.
The fun part was figuring out how to make everything work with one button.
Instead of choosing from a long menu, players pick a brewer, adjust the strength, and add ingredients like milk, ice, or different flavors. With 6 brewers, 6 mix-ins, and 5 flavors, there are 180 possible combinations.
Here's a small part of the code that handles the automatically cycling options:
function i=pick(s,p)
i=1+mod(floor(s.t/.95),numel(s.menu{p-1}));
end
The timer keeps moving through the available choices every 0.95 seconds, and pressing Space selects whichever option is highlighted.
I also reused graphics objects for the animations, so the coffee changes color when milk is added, ice appears in cold drinks, and the cup slides across the counter when served.
It's been fun experimenting with how much you can do in MATLAB while staying within the 10,000-character limit.

I made TOP BINS — PENALTY SHOOTOUT using MATLAB and Codex, and wanted to share a small trick I used for the one-button controls.
The idea is simple: the target keeps moving around the goal using sine and cosine. Pressing SPACE locks the aim, and then a power slider starts moving automatically. Press SPACE again to shoot at the selected power.
I used different game modes to make the same button do both things:
s.t = s.t + dt;
if s.mode == 1 && tap
s.mode = 2;
s.t = 0;
elseif s.mode == 1
s.aim = aimAt(s);
elseif s.mode == 2
s.p = 1 - abs(1 - mod(.79*s.t, 2));
if tap
s = launch(s);
end
end
The green power range also changes depending on where you're aiming, so each shot needs slightly different timing.
It's a simple way to get two different actions out of just one button. Thought it might be useful for anyone making a game for the Mini Hack. Also you can notice the cheeky billboard ad with MATLAB on it and the crowd :D
Here's my game, ENJOY!: https://www.mathworks.com/matlabcentral/communitycontests/contests/10/entries/16673

- Optimize AST, not whitespace: tree2str expands spacing back out, so save characters by cutting duplicate variables, struct fields, and repeated property strings—not spaces.
- Use complex numbers (x + 1i*y) for 2D math: One array holds both X and Y, abs(z1 - z2) handles hitboxes, and z .* exp(1i*theta) rotates shapes in one step.
- Batch sprites into single handles: Pre-allocate one patch or line per object type in init, then update all active instances at once with NaN-separated vectors.
- Wrap repeated graphics calls: Short inline handles like p=@(x,y,c)patch(ax,x,y,c,'EdgeColor','none','HitTest','off') save hundreds of characters across UI and sprites.
- Pack scalar state into one vector: Store timers, score, lives, and flags in a single numeric array v instead of separate struct fields.
The MATLAB One-Button Game Mini Hack does not allow commonly used audio functions such as sound and audioplayer. However, two other built-in functions, uihtml and sendEventToHTMLSource, are available. By combining these functions with HTML and JavaScript, you can play background music and sound effects in your game!
Here is a working example:
Feel free to check it out!
I made a little game called TIDE//SHIFT for the One-Button Game Mini Hack using MATLAB and Codex.
One thing I experimented with was adding momentum to the movement. Instead of instantly changing direction when you press Space, the character drifts a little before turning.
I used a simple damping formula:
target = 110 * polarity;
blend = 1 - exp(-4.4 * dt);
v = v + (target - v) * blend;
A small change, but it makes the game much more fun to control.
If you're making a one-button game, try experimenting with momentum. It really changes how the game feels.

Four (of many) new features for Apps in MATLAB R2021a
These four new features are the solutions to many inquiries in the Answers forum that continue to receive hundreds of views per month long after they were asked.

Table of Contents
- Keyboard Shortcuts for UI Components
- Programmatically scroll UITables
- Figure always on top
- UI hyperlink component
- Demo app: Keyboard shortcut challenge
Keyboard Shortcuts for UI Components
Keyboard shortcuts can now change the focus and make contiguous and non-contiguous selections in ListBox, Table, DatePicker, and ColorPicker menus created in uifigures. The table below summarizes the shortcuts made available in R2021a ( release notes ).

Reminder: in MATLAB R2020b and later you can change the tab order of objects in an app by changing their stack order in AppDesigner using the Reorder tool in the drop-down menu or by right-clicking the component and selecting Reorder from the menu (see R2020b release notes and a screenshot in the Answers forum ).
Programmatically scroll UITables
The scroll function was added in R2016a but as of R2021a it can be used with uitables to programmatically scroll to the top, bottom, left, or right of a table or to a specific row, column or cell ( release notes ). Combined with a uistyle (R2019b) you can scroll to and highlight any part of the uitable.
Syntax examples:
- scroll(uit,vlocation) where vlocation is 'top'-'bottom'
- scroll(uit,hlocation) where hlocation is 'left'-'right'
- scroll(uit,target,targetIndex) where target is 'row'-'column'-'cell' and targetIndex is a row or column number or a 1x2 cell location.
Figure always on top
Figures created with uifigure now have an additional WindowStyle property: 'alwaysontop' ( release notes ). Figures with this setting will stay on top of other windows but unlike the modal option, other windows are still accessible.
To toggle the AlwaysOnTop state of your app using a checkbox, state button, or another UI component, follow this callback function template,
function alwaysOnTopCheckBoxValueChanged(app, event)
value = app.alwaysOnTopCheckBox.Value;
if value
app.UIFigure.WindowStyle = 'alwaysontop';
else
app.UIFigure.WindowStyle = 'normal';
end
end
UI hyperlink component
Use the uihyperlink function or the UI hyperlink component in App Designer or a uifigure to add and configure a clickable link ( release notes ). The hyperlink can be assigned to a figure, panel object, tab object, ButtonGroup, or GridLayout object when created in a uifigure. In addition to setting the text and URL, there are lots of properties to control the text format including the VisitedColor property that controls the color of the text after the link is clicked and an optional user-defined HyperlinkClickedFcn function that is evoked when the link is clicked.
Demo app: Keyboard shortcut challenge
The attached zip file contains an app, keyboardShortcutsDemo_R2021a.mlapp , that demonstrates these 4 features. The app displays the extent of arctic sea ice from 1979 to 2016 during the months when extent typically maximizes and minimizes.
Mouseless challenge: After opening the app, without using your mouse, try the following.
- Select a month (September or March) and any number of years from the list boxes
- Navigate through the Date Picker and select a date within the range or your selected years (disabled when only 1 year is selected).
- Navigate to the always-on-top checkbox to pin the app to the top of other windows.
- Navigate to the text box and enter a year that appears in the uitable to go to that row in the uitable (disabled when only 1 year is selected).
- Navigate to the URL and press Enter to open the website containing the raw data.

Download the attached zip file, FourNewAppFeatures_R2021a.zip, for a Live script copy of this thread and an app that demonstrates each feature.

Starting in r2020a, AppDesigner buttons and TreeNodes can display animated GIFs, SVG, and truecolor image arrays.
Every component in the App above is either a Button or a TreeNode!
Prior to r2020a the icon property of buttons and TreeNodes in AppDesigner supported JPEG, PNG, or GIF image files specified by a character vector or string array but did not support animation.
Here's how to display an animated GIF, SVG, or truecolor image in an App button or TreeNode starting in r2020a. And for the record, "GIF" is pronounced with a hard-g .
Display an animated GIF
Select the button or TreeNode from within AppDesigner > Design View and navigate to Component Browser > Inspector > Button dropdown list of properties (shown below). Select an animated GIF file and set the text and icon alignment properties.

To set the icon property programmatically,
app.Button.Icon = 'launch.gif'; % or "launch.gif"
The filename can be an image file on the Matlab path (see addpath ) or a full path to an image file.
Display SVG
Use “scalable vector graphics” files for high-resolution images that are scaled to different sizes while preserving their shape and retaining their clarity. A quick and easy way to remember which plotting function is assigned to each button in an app is to assign an image of the plot to the button.
After creating the figure, expand the axes by setting the position or outerposition property to [0 0 1 1] in normalized units and save the figure using File > Save as and select svg format. Save the image to the folder containing your app. Then follow the same procedure as animated GIFs.

Display truecolor image
A truecolor image comes in the form of an [m x n x 3] array where each m x n pixel color is specified by an RGB triplet (read more) . This feature allows you to dynamically create a digital image or to upload an image from a mat file rather than an image file.
In this example, a progress bar is created within the uibutton callback function and it’s updated within a loop. For a complete demo of this feature see this comment .

% Button pushed function: ProcessDataButton
function ProcessDataButtonPushed(app, event)
% Change button name to "Processing"
app.ProcessDataButton.Text = 'Processing...';
% Put text on top of icon
app.ProcessDataButton.IconAlignment = 'bottom';
% Create waitbar with same color as button
wbar = permute(repmat(app.ProcessDataButton.BackgroundColor,15,1,200),[1,3,2]);
% Black frame around waitbar
wbar([1,end],:,:) = 0;
wbar(:,[1,end],:) = 0;
% Load the empty waitbar to the button
app.ProcessDataButton.Icon = wbar;
% Loop through something and update waitbar
n = 10;
for i = 1:n
% Update image data (royalblue)
% if mod(i,10)==0 % update every 10 cycles; improves efficiency
currentProg = min(round((size(wbar,2)-2)*(i/n)),size(wbar,2)-2);
RGB = app.ProcessDataButton.Icon;
RGB(2:end-1, 2:currentProg+1, 1) = 0.25391; % (royalblue)
RGB(2:end-1, 2:currentProg+1, 2) = 0.41016;
RGB(2:end-1, 2:currentProg+1, 3) = 0.87891;
app.ProcessDataButton.Icon = RGB;
% Pause to slow down animation
pause(.3)
% end
end
% remove waitbar
app.ProcessDataButton.Icon = '';
% Change button name
app.ProcessDataButton.Text = 'Process Data';
end
The for-loop above was improved on Feb-11-2022.
Credit for the black & teal GIF icons: lordicon.com
How to Play
In Circuit Runner, your goal is to make your way through a series of logic gates while staying ahead of the glitch chasing you.
Each gate has a set of binary inputs, either 0 or 1. Work out what the output should be and press when the scanner highlights the correct path.
- Upper path: Output 1
- Lower path: Output 0
Your first press locks in your answer for that gate, so make sure the correct path is highlighted before pressing.
If you choose the wrong path or fail to answer in time, your signal gets jammed, allowing the glitch to catch up. Keep getting the answers right to stay ahead!
STEM Concept: Boolean Logic
Boolean logic is the basis of how digital circuits work. It uses two possible values, 0 and 1, which can also represent false and true.
Logic gates take one or more binary inputs and produce an output based on a particular rule.
For example, an AND gate only produces an output of 1 when both its inputs are 1. An OR gate, on the other hand, produces 1 when at least one input is 1.
In this game, you'll come across different gates and need to quickly figure out their outputs. This is the same process used to construct truth tables in digital logic.
Timing Your Press!
You'll need to think quickly as the game progresses.
- Read the gate and its inputs as soon as they appear. Try to work out the output before looking at the scanner.
- The scanner starts at 0 for every new gate and switches between the two paths. Press when it highlights your answer.
- As you move through the stages, the scanner switches faster and the gates approach more quickly, giving you less time to decide.
- Try to get three correct answers in a row to activate a two-second speed boost. Every correct answer also helps you get further ahead of the glitch.
Getting an answer wrong temporarily jams your signal, so it's worth checking your answer rather than pressing too early.
Logic Gate Reference
Here's a quick reference for the gates you'll encounter:
- AND: Outputs 1 only when both inputs are 1.
- OR: Outputs 1 when at least one input is 1.
- NOT: Reverses the input. If the input is 0, the output is 1, and vice versa.
- XOR: Outputs 1 when the two inputs are different.
- NAND: Outputs 1 when at least one input is 0.
- NOR: Outputs 1 only when both inputs are 0.
- XNOR: Outputs 1 when both inputs are the same.
A useful way to remember the gates is that NAND, NOR and XNOR are simply the opposites of AND, OR and XOR respectively.
If you're unsure about a gate, try thinking about when its output would be 0 instead.
How It Works in MATLAB!
The game uses MATLAB's logical operations to calculate the correct output for each gate.
At the start of each stage, the available gate types are shuffled to give you a different sequence of questions.
The game continuously updates the scanner as it switches between the two paths. When you press, MATLAB locks in the output that was highlighted on the last displayed frame and checks it against the correct answer.
The graphics are updated throughout the game to show the track, scanner position, score and distance from the glitch.
As you play, try to get familiar with the different gates rather than calculating each output from scratch. Once you recognise their patterns, answering becomes much faster, which is exactly what you'll need in the later stages.
EVERDROP is a falling-block game on a five-column board, played with a single button. The contest harness gives a game exactly one signal, pressed, which is true on the frame a tap arrives. There is no hold, no release and no mouse position. Here are three things that made the game work inside those limits, and a short story of how it was built.

Time-lapse of the game, played by a small test bot through the same tap input.
1. Two actions from one tap: act first, undo later
I wanted two moves: rotate the piece, and shift it sideways. The obvious way is to wait a moment after a tap to see whether a second one follows. That makes every rotation feel late.
So the first tap rotates at once and remembers the old shape. If a second tap comes within 0.3 seconds, the rotation is taken back and the piece moves one column instead.
if pressed
if s.tap < 0.3 && ~isempty(s.undoShape)
s = undoRotation(s);
s = stepSideways(s);
else
s.undoShape = s.shape;
s.undoCol = s.pc;
s = rotatePiece(s);
end
s.tap = 0;
end
s.tap is the time since the last tap, increased by dt every frame. Sideways movement goes right until the wall, then left, so one direction is enough.
2. Pixel art as text
imread is on the banned list, so a picture has to live in the code. I store it as a character matrix, one character per pixel, and turn it into colours with ismember:
art = ['....WW......WW...........'
'...BBBB....BBBB..........']; % 20 rows in the game
[~, idx] = ismember(art, '.BWKO');
image(ax, 'XData', [651 795], 'YData', [323 437], ...
'CData', reshape(shades(idx, :), [size(art), 3]), ...
'AlphaData', idx > 1);
shades is a small colour table with one row per letter. The dot is transparent through AlphaData. A 25 by 20 picture costs about 600 characters, and you can edit it in the MATLAB editor like a drawing.
3. Many lines, one graphics object
The floor grid and the mountain ridges are each a single line. Separate segments are joined by putting NaN between them in the coordinate vectors. The whole background is a handful of objects created once in init, and render never touches them.
One more small thing
The blinking prompt needs no timer. render sets its visibility from the running clock in the state: mod(s.clock, 0.8) < 0.55. Calling render twice with the same state gives the same picture, as the contract asks.
How it was built: one evening with an AI assistant
I built EVERDROP in one evening, working with an AI coding assistant (Claude), mostly from my phone. I described the idea in one sentence, asked for a sketch of the screen first, and then steered: how pieces move, what a tap does, what the screen should look like. The assistant wrote the code and ran it in my MATLAB with simulated taps after every change, so most mistakes were caught before I saw them.
Three things I learned:
- Read the rules first. We spent hours on a version with sound, a window of its own and a hold-to-drop control. Then we read the contest rules: 10,000 characters, no audio functions, and a harness that only reports taps. The entry had to be rebuilt from the ideas, not the code. Hold-to-drop did not survive.
- The AI tests logic, not feel. It could prove that a double tap moves a piece. It could not tell me whether 0.3 seconds feels right under a real finger. That part was mine.
- Short instructions work, if you look at every result. Most of my messages were one line: "green on black", "remove moving lines", "add mountains". Each time I got a screenshot back and decided again. It also said no a few times. When I showed it a picture to copy, it drew its own instead.
The validator in the starter project made the loop safe: change, validate, play, repeat.
The game uses 8,731 of the 10,000 characters. You can play it here: https://www.mathworks.com/matlabcentral/communitycontests/contests/10/entries/16663
In MATChess, you play chess against MATLAB with only your mouse click. MATLAB plays white and moves first. You play the dark pieces. Click a piece, then click a green square. That is all you need.
The goal is not just to move pieces. It is to think one step ahead of MATLAB, and to choose the level that matches your skill.
Play the game
Entry page: MATChess
Open the entry, click Play Game, then click Run this app in MATLAB Drive.

The start of a game. MATLAB (white) has made its first move. Now it is your turn.
How to play
- MATLAB moves first. Wait until the top line says Your move.
- Click one of your dark pieces.
- Green squares show every legal move for that piece.
- Click a green square to make your move.
- When the game ends, click anywhere to play again.
The game only lets you make legal moves. You cannot make a move that leaves your own king in check.

A dark knight is selected. Green squares show where it can go. Yellow squares show MATLAB's last move.
What the colours mean

The line at the top tells you what is happening: Your move., CHECK! Your move., MATLAB is thinking..., or the result when the game ends.

MATLAB is thinking. After your move, it waits half a second and then replies.
Choose your level
There are three buttons on the left side of the board: EASY, NORMAL and TOUGH. Click a button to start a new game at that level. The orange button shows the level you are playing. The game starts on NORMAL.

Try this: play the same first moves on EASY and on TOUGH. Where does MATLAB start to play differently?
How MATLAB chooses a move
MATLAB gives every position a score. A higher score is better for MATLAB. The score has three parts:
- Piece value: pawn 100, knight 320, bishop 330, rook 500, queen 900, king 20,000.
- Centre bonus: knights and bishops get extra points when they stand near the centre of the board.
- Pawn push: pawns get extra points as they move forward.
Then MATLAB tries its moves and your replies, and keeps the move with the best score. It looks at captures first, so it can skip weak moves faster. This idea is called alpha-beta pruning. The king is worth so much that losing it ends the search, and a quicker win scores a little higher.
The rules in the game
Included:
- All normal moves for every piece.
- Pawns can move two squares from their first row.
- Check, checkmate and stalemate.
- A pawn that reaches the last row becomes a queen.
Not included:
- Castling and en passant.
- Draw by repetition and the 50-move rule.
- Choosing a piece other than a queen when a pawn is promoted.
One click does every job
The game uses just one input: a click. Each click does one job, depending on where you click and what is happening:
- Click a level button: start a new game at that level.
- Click one of your pieces: select it.
- Click a green square: move the selected piece.
- Click after the game ends: play again.
Each square is 66 pixels wide. The game turns the click position into a column and a row with ceil((x-136)/66) and ceil((y-50)/66). After the game ends, it waits half a second before it accepts a click. This stops a quick click from hiding the result.
How the board is drawn
The board is stored as an 8-by-8 matrix. Positive numbers are MATLAB's white pieces and negative numbers are your dark pieces. The numbers are 1 pawn, 2 knight, 3 bishop, 4 rook, 5 queen, 6 king, and 0 for an empty square. A move is four numbers: the start row and column, and the end row and column.
The code is split into three parts: initialize, update and render. The graphics are created once and then reused. The board is one patch object with 64 squares, and only the colours change from frame to frame. The pieces are Unicode chess symbols in text objects. Each piece is drawn twice: a bigger black symbol behind and a smaller coloured symbol on top. This gives every piece a dark outline.
Try this
- Can you beat TOUGH? How many moves does it take?
- Play on EASY and try to catch MATLAB's random mistakes.
- Can you trap a piece with a knight fork?
Which level can you beat? Tell me in the comments. Thank you for playing!
How to Play
The goal of Descent is to move the ball to the lowest point of the curve using gradient descent.
Watch the moving meter and press to select a learning rate. Each press moves the ball one step and uses up one move.
To complete a stage, you need to get within 0.06 of the target position before running out of moves. If the ball moves outside the plotted range, the game ends.
STEM Concept: Gradient Descent
Gradient descent is a method used to minimize a function, such as the loss function used when training machine learning models.
In this game, the slope of the curve tells you which direction to move, while the learning rate controls how far you move in that direction.
- A small learning rate gives you smaller steps, which are safer but may take longer to reach the minimum.
- A large learning rate gives you bigger steps, which can get you there faster but may also cause you to overshoot.
The challenge is to choose a learning rate that gets you close to the minimum without taking unnecessary steps.
Choosing a Learning Rate
Use the tangent line to understand the slope at your current position. After each move, check the loss value to see whether your choice helped.
For the first three stages, the meter is colour-coded:
- Cyan: Moves you closer to the minimum quickly.
- Amber: May overshoot the minimum but can still reduce the loss.
- Red: May increase the loss instead of reducing it.
The last two stages have a neutral meter, so you'll need to judge the learning rate using the curve and the feedback from your previous moves.
A Few Hints for Each Stage :)
- First Contact: Try a learning rate of 1.000.
- The Steep Valley: The curve is steeper, so try a smaller rate of 0.250.
- Low Gravity: The slope is gentler, so a larger rate of around 3.333 works well.
- Shifted Reality: Try aiming for 0.625.
- The Final Descent: Start with smaller steps where the curve is steep. As you get closer to the minimum, you can try increasing the learning rate.
In the first four stages, the loss function has the form:
Loss = a * (x - target)^2 + minimumLoss
For these curves, a learning rate of 1 / (2 * a) will take you directly to the minimum in one step.
Try to finish each stage with as many moves remaining as possible to earn a higher score!
How It Works in MATLAB
Every time you press, the game updates the ball's position using the gradient descent rule:
x_new = x - alpha * gradient
Here, x is your current position, alpha is the learning rate you selected, and gradient is the slope of the curve at that position.
MATLAB calculates the gradient from the derivative of the loss function and moves the ball to its new position.
The final stage uses a slightly more complicated function with a quartic term. This means the learning rate needed to reach the minimum in one step changes depending on your current position.
As you play, try experimenting with different learning rates and observe how they affect the ball's movement and the loss. The idea is to get a feel for why choosing the right learning rate matters when using gradient descent.
关于 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!
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!
更多社区版块
MATLAB Answers
提出和回答关于 MATLAB 和 Simulink 的问题!
File Exchange
下载或贡献用户提交的代码!
Cody
解题组,学习 MATLAB 并赢取徽章!
博客
MATLAB 和 Simulink 探秘!
AI Chat Playground
使用 AI 生成 MATLAB 代码初始草稿,并回答问题!



