MATLAB Community https://blogs.mathworks.com/community News from the intersection of MATLAB, Community, and the web. Sun, 07 Jan 2024 22:07:02 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.2 Newton’s Method Fractals https://blogs.mathworks.com/community/2023/12/05/newtons_method_fractals/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/12/05/newtons_method_fractals/#comments Tue, 05 Dec 2023 22:31:06 +0000 https://blogs.mathworks.com/community/?p=9757

Recently I've seen a number of fractal images created with Newton's method. For instance, Daniel Pereira had two spectacular animations in the recent Flipbook Mini-Hack contest. Rotating Newton's... read more >>

]]>
Recently I've seen a number of fractal images created with Newton's method. For instance, Daniel Pereira had two spectacular animations in the recent Flipbook Mini-Hack contest.

Here's another example of the kind of picture I'm talking about.


How is such an image made? What does it represent? It's one of those things where complexity is hiding behind something that, on its face, seems straightforward.

To motivate this, consider this question: How do you find the roots of this polynomial?

x3 - 2·x2 - 11·x + 12.

That is, for what values of x is this equation true? x3 - 2·x2 - 11·x + 12 = 0

There are a number of ways to answer this question. If you’re good at factoring polynomials, you might recognize that this is (x-4)(x-1)(x+3). Another answer is to use a little MATLAB magic. MATLAB represents polynomials as vectors containing the coefficients ordered by descending powers. Here is that same polynomial in vector form.

>> p = [1 -2 -11 12]

Once in the right form, there’s a command ROOTS that will answer our question directly.

>> roots(p)
ans = 
  -3.0000 
   4.0000 
   1.0000

But let's say that your polynomial won't factor so easily, and you don't have a computer handy. Let’s imagine you're Isaac Newton and you want to find the roots of this polynomial. Now what?

As it happens, Newton is credited with a nifty iterative method for finding the roots in a situation like this. You start with a guess, and you use the slope of the curve at that point to make a better guess. Keep repeating this process until you get as close as you want to zero.

Let's start with a guess at -1.9.

x=-1.9000, f(x)=18.8210
x=-4.4331, f(x)=-65.6622
x=-3.4335, f(x)=-14.2877
x=-3.0585, f(x)=-1.6770
x=-3.0013, f(x)=-0.0364
x=-3.0000, f(x)=-0.0000

If we start at -1.9, we end up finding the root at -3 in around six iterations. But wait! There are three roots to this polynomial. It turns out that different starting locations will converge to different roots. So for every starting guess, there is a corresponding root. This is where things get interesting.

This iterative process maps an initial guess to a root. You can think of the resulting map as being divided into basins. Different basins drain into different roots. We can color these basins according to the root to which that starting point will eventually converge. Additionally, we'll keep track of how many iterations it takes to converge (that is, to reach the same tolerance). The curve in the top graph is colored according its corresponding root. Each colored region represents a different basin.

Curiously, these basins aren't always well defined. As we zoom into the boundaries between two basins, we keep finding smaller and smaller regions that converge to different roots. This back-and-forth convergence continues no matter how much you zoom in. This phenomenon is sometimes called a fractal basin boundary.

Now that we've demonstrated this for the real number line, you may wonder: can we generalize to the complex plane? Yes we can, because MATLAB is awesome! Since complex numbers are a native data type, you can use exactly the same code as in the one dimensional case.

So let's examine a more complicated polynomial. This one has complex roots. We'll use the process shown above to find the root basins on the complex plane.

What are the roots of this polynomial?

8·x7 + x6 + 3·x5 + 7·x4 + 2·x3 + 4·x2 + 5·x + 6

Since it is a seventh order polynomial, there are seven roots to this equation. Every point on the complex plane maps to one of them. So every single pixel in this plot is the result of Newton's method. But the borders between these regions are demented fractals.

Look how simple the code is! There's only one line right in the middle that's doing all the heavy lifting.

p = [8 1 3 7 2 4 5 6];

% Make anonymous functions for the polynomial and its derivative.
f  = @(x) polyval(p,x);
df = @(x) polyval(polyder(p),x);

span = linspace(-1.5,1.5,300);
[x,y] = meshgrid(span,span);
z = x + 1i*y;

% Apply Newton's method
for k = 1:50
  z = z - f(z)./df(z);
end

% Use ANGLE as a proxy to display the root
imagesc(span,span,angle(z))
axis square

% Show the roots
hold on
plot(roots(p), ...
  LineStyle="none", ...
  Marker="pentagram", ...
  MarkerFaceColor="red", ...
  MarkerSize=18)
hold off

And how many iterations did it take at each point to converge to that root? That's the picture we started with at the top of the post.

Now that you know the basics, it’s easy to make some eye-popping animations. Here's one of my own additions to the recent Flipbook contest.

If you want to learn more, take a look at Cleve's post on this topic: Fractal Global Behavior of Newton’s Method.

]]>
https://blogs.mathworks.com/community/2023/12/05/newtons_method_fractals/feed/ 2
🚀 The MATLAB AI Chat Playground Has Launched https://blogs.mathworks.com/community/2023/11/07/the-matlab-ai-chat-playground-has-launched/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/11/07/the-matlab-ai-chat-playground-has-launched/#comments Tue, 07 Nov 2023 18:31:24 +0000 https://blogs.mathworks.com/community/?p=9665

The MATLAB AI Chat Playground is ready for you to experiment with Generative AI, answer questions, and write initial draft MATLAB® code. All of us on the community team share a guiding principle. We... read more >>

]]>
The MATLAB AI Chat Playground is ready for you to experiment with Generative AI, answer questions, and write initial draft MATLAB® code.

All of us on the community team share a guiding principle. We wake up every day thinking about how we can help our users accelerate their pace of learning and building. ChatGPT, Generative AI, and large-language model (LLM) technology have been sweeping forces, and we see this amazing technology as a tool that, if applied correctly, can help users find answers, get initial drafts of code, and help break down complex engineering problems.

We spent this year listening to you, experimenting with Generative AI ourselves, and building a space for our users to experiment. We have been working with our top community users and refining the experience, and I am thrilled to announce that we are now opening the MATLAB AI Chat Playground to all users.

To get access right now, go to the MATLAB Central community and select AI Chat Playground.

Known Limitations

The AI Chat Playground is optimized to assist with MATLAB-related input, including toolboxes for deep learning, statistics and machine learning, optimization, control systems, and signal processing. Currently, the system has limited knowledge of Simulink and other MathWorks products.

How to use the MATLAB AI Chat Playground

Open the AI Chat Playground in a desktop browser.

MATLAB AI Chat Playground

The playground features a chat panel next to a lightweight MATLAB code editor. Use the chat panel to enter natural language prompts to return explanations and code. You can keep chatting with the AI to refine the results or make changes to the output.

Try one of the onboarding prompts if you don’t know where to start.

The AI replies with an explanation, some code, and follow-up prompts to keep the conversation going. At any point, you can enter your own input and explore an endless number of directions. Every time I use the playground, I learn about features of MATLAB, ways to interface with functions, or new concepts. I am always picking up new things.

If you want to try the MATLAB code, select the insert icon next to the code and then click the run button. This will execute the code and show the results. If you want to copy the code and bring it into the MATLAB editor or Visual Studio Code, select the copy button.

Please rate the output of the AI with the thumbs up or thumbs down buttons. This is an important signal for us to figure out how to improve the output and refine the experience over time.

Use Cases

Here are some use cases for the playground that others have found helpful.

Ask Questions

A good place to start is to ask basic technical computing questions.

  • What's an eigenvalue?
  • How do I customize a line plot?

Generate Ideas

If you don’t have a specific question, you can also use the AI Chat Playground to generate ideas on how to do something.

  • Give me some ideas on how to visualize large amounts of rainfall data.
  • My data is noisy. What can I do to fix it?

Get Code

A powerful way to use the playground is to get MATLAB code. Try entering some high-level instructions.

  • Create some data, construct a grid of query points, interpolate the grid, and plot the results.
  • Roll two six-sided dice 1000 times and plot the sum of each roll.

Inspiration

I look forward to seeing what you learn and build with the MATLAB AI Chat Playground. Please share your experiences here and in the Generative AI discussion area of the MATLAB Central community. It’s important that we inspire each other and collectively learn how to harness this powerful technology. We are all in this together.

]]>
https://blogs.mathworks.com/community/2023/11/07/the-matlab-ai-chat-playground-has-launched/feed/ 13
Contest Animations with INTERP1 https://blogs.mathworks.com/community/2023/11/06/contest-animations-with-interp1/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/11/06/contest-animations-with-interp1/#respond Mon, 06 Nov 2023 21:06:50 +0000 https://blogs.mathworks.com/community/?p=9737

Today we're launching a new contest here on MATLAB Central: the MATLAB Flipbook Mini Hack. Why flipbook? It's an animation contest in which each animation gets exactly 48 frames, so it's like... read more >>

]]>
Today we're launching a new contest here on MATLAB Central: the MATLAB Flipbook Mini Hack. Why flipbook? It's an animation contest in which each animation gets exactly 48 frames, so it's like flipping through a 48-page pad of paper with slightly different drawings on each page. Check it out: entries are already pouring in!
contest.png
In this post, I want to demonstrate some coding techniques that can make your animations easier. Suppose, for example, you wanted to animate a dot moving in a circle. Here the variable f is the frame number. It will take on the values from 1 to 48.
f = 1:48;
We want to use f to help us make an dot move in a circle. As f increments up to 48, we'll make the variable theta go from 0 to 2 pi. A perfect job for INTERP1! The INTERP1 function is a convenient way to do a linear map from one domain to another.
theta = interp1([0 48],[0 2*pi],f);
plot(f,theta,'.-',MarkerSize=12)
Let's pretty up this plot.
xlim([1 48])
ylim([0 2*pi])
set(gca,XTick=0:8:48)
set(gca,YTick=pi*(0:0.5:2),YTickLabel={"0","\pi/2","\pi","3\pi/2","2\pi"})
xlabel("Frame Number")
ylabel("Theta")
grid on
This shows you how theta varies across all frames. It's all pretty straightforward, but I just love how INTERP1 washes away the hassle of working out the linear mapping.
Now it's time to build one frame of our animation. So instead of looking at all values of f, we'll just consider one. Appropriately, we'll start with frame 1.
f = 1;
Now we use our interpolation trick to map frame number into theta.
theta = interp1([0 48],[0 2*pi],f);
With theta defined, it's time to plot our moving dot. A little trig will put the dot in the right place.
plot(cos(theta),sin(theta),".", ...
MarkerSize=24)
Not much to look at so far! Let's make a circular race track that doesn't move so we can follow the action more clearly.
t = linspace(0,2*pi);
line(cos(t),sin(t))
And we'll square up the axis and reset the limits so the dot isn't bumping into the edges.
axis square
axis([-2 2 -2 2])
Now we have the code that we put into the contest entry page. This code will create any of the frames 1 through 48 on demand. When you push the "Create Animation" button, the contest machinery does the rest of the magic. It generates all 48 frames in succession and stitches them into a single GIF image.
Here is the result.
racetrack.gif
There you have it: a two-second 48-frame movie masterpiece! I call it "Cutting a Hole in the Wall with a Blue Laser". Or "Blue Polar Bear Circles the North Pole". What would you call it?
That was a simple way to get started, but I feel we can do better. Let's do something more interesting with this circular motion.
First set up a landscape.
% Set up a landscape
peaks
z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2)
shading flat
material dull
axis vis3d off
Nice! Now we're going to create a light and move it around above this landscape. We can use our interpolation trick.
% Just showing frame 1 here
f = 1;
% Map onto theta
theta = interp1([0 48],[0 2*pi],f);
% Set up the light
ht = 4*sin(theta) + 4;
pos = [2*cos(theta) 2*sin(theta) ht];
light(Position=pos)
% The actual light is invisible, so we'll mark its position with a yellow dot
line(pos(1),pos(2),pos(3), ...
Marker=".",MarkerSize=24,Color="y")
set(gcf,Color=0.8*[1 1 1])
Now as f changes, the light orbits around the landscape in three dimensions. Here's the final animation. Pretty cool, eh? It's certainly better than our first animation.
orbit2.gif
I have found this contest to be a lot of fun, and very addictive. Maybe you will to. I encourage you to give it a try. Now that you know the INTERP1 trick, you have the secret to making your images dance.

]]>
https://blogs.mathworks.com/community/2023/11/06/contest-animations-with-interp1/feed/ 0
Head-to-Head Voting: Which Solution Is the Best Solution? https://blogs.mathworks.com/community/2023/09/22/head-to-head-voting-which-solution-is-the-best-solution/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/09/22/head-to-head-voting-which-solution-is-the-best-solution/#comments Fri, 22 Sep 2023 18:23:36 +0000 https://blogs.mathworks.com/community/?p=9581

I like to play Cody because I always learn something. After I've solved a problem, I spend a little time with the Solution Map looking at other solutions. It doesn't take long to find something... read more >>

]]>
I like to play Cody because I always learn something. After I've solved a problem, I spend a little time with the Solution Map looking at other solutions. It doesn't take long to find something better, and often I learn about a function that I never knew existed.

For instance, have you ever heard of the function ISSORTED? It's a simple function, but it was new to me. Let me tell you how I first learned about it. Along the way, I'll tell you about a new trick for finding good Cody solutions.

Let's consider Cody Problem 10, which is about monotonically increasing vectors. Here's the problem statement: Return true if each element in the input vector is larger than its predecessor.

At the moment I write this, Problem 10 has over 67,319 solutions. Quick! Which one is the best? It's a daunting request. But the best solution out of a set that big is probably pretty good. Certainly worth a look. But which one is it?

We can start with a simple distinction: of all these solutions, only 20,813 are correct. So that's progress! The best solution is likely to be in this subset. Which of these correct answers is the best? Cody uses a metric, called "size," to rank the solutions. A solution's size is the number of nodes in the parse tree for a given solution, and lower is considered better. It's a useful metric, but far from perfect. We all know that the shortest solutions aren't always the best solutions. Indeed, because of some weird hacks that people have worked out (cough cough, regexp), the shortest solution is often a terrible solution in real life.

If size isn't a great metric, can we come up with a better one? In general, it's difficult, maybe impossible, to come up with an automated system that can figure out which solution is the best. What criteria are you using? Size? Speed? Efficiency? Readability? And how do you weight each of these? Would you sacrifice readability for the sake of speed, or vice versa? Everybody has a different notion of goodness.

Ultimately, what most of us want to know is this: Which solution do most people prefer? It's a utilitarian answer that relies on the wisdom of the crowd. We're acknowledging that judging code is subjective, and we're asking our friends and neighbors to apply their subjectivity, biases and all. This turns out to work pretty well.

Head-to-Head Ranking

Now that we've decided to make a subjective judgment system, we have to work through some practical issues. How do you get people to give fair and distinct scores to thousands of solutions? Here is the key insight: whereas it's difficult to grade individual entries consistently, it is generally straightforward to compare two entries and say which one is better. And once we've built up enough binary comparisons, we can use statistics to work out scores for all the solutions. Here we rely on techniques (the Bradley-Terry algorithm, in this case) developed for ranking players in sports and games. Think about how a collection of chess or tennis matches can be aggregated into one global ranking.

A few months ago, Cody added a crowd-scoring feature based on this head-to-head comparison approach. Now we can tell you not only which code is the smallest, but also which code is preferred by the people who are playing.

Let's look at a set of solutions to Problem 10 that have all been ranked. Here is a histogram by size. The median size is 37.

Things get more interesting when we plot crowd score vs. size. Crowd score is what we're calling the subjective ranking applied by players like you. This number is the output of the Bradley-Terry algorithm, and it's been normalized here so that the best crowd score is 100.

There is an obvious skew to the distribution: preferred solutions tend to be shorter.

We should note here that the great majority of solutions have not been given a crowd score yet, so we can't expect the results to be comprehensive and consistent. Similar entries may receive different ratings. Nevertheless, the plot is instructive. It extracts good entries from the vast amount of background noise.

The red arrow indicates the current crowd favorite:

In English we might say: in all cases, the difference between two successive elements should be positive. Compact and easy to read! This use of DIFF is a nice example of vectorized code. You don't need a loop to go through all the elements of x. But you can if you want to. Here is a longer, less preferred solution.

It still gets the correct answer, but the code is longer (and arguably, harder to read) because it explicitly loops through the vector x.

Here is a plot that distinguishes between those solutions that use the vectorized DIFF approach and those that use the looping LENGTH approach. Vectorization leads to shorter, and generally more preferred code.

There are many variants on the DIFF theme. For instance, this one is slightly more complicated than the leader.

Here's one that is still vectorized, but it does the DIFF calculation explicitly.

There are some other intriguing entries from the list of preferred solutions. I like this one. Here the function UNIQUE is enforcing the problem criteria: if the vector is already in the order that would be returned by UNIQUE, then you're good.

And finally, here's the one from farther down the list that took me by surprise.

I didn't even know about the ISSORTED function, but it's been around for a long time, and it offers the shortest, most direct solution to the problem.

Which one of these is your favorite, and why?

I love solution tourism in Cody. Where else can you be exposed to so many novel functions and solution methods? Even so, the full list of Cody solutions can feel like an impenetrable jungle. Where do you start? That's why we introduced solution voting: to find the treasures hidden in the thicket.

And if you like this feature, remember that it's only as good as the votes going into it. Please spend a little time voting on answers yourself. It only takes a little effort, and everybody wins!

]]>
https://blogs.mathworks.com/community/2023/09/22/head-to-head-voting-which-solution-is-the-best-solution/feed/ 3
Continued Fractions and Computations https://blogs.mathworks.com/community/2023/07/17/continued-fractions-and-computations/?s_tid=feedtopost Mon, 17 Jul 2023 21:57:55 +0000 https://blogs.mathworks.com/community/?p=9470

Today's guest article is by Wesley Hamilton, a STEM Outreach engineer here at MathWorks. See his earlier piece on solving Sudoku puzzles. In this blog post we'll explore the fascinating world of... read more >>

]]>
Today's guest article is by Wesley Hamilton, a STEM Outreach engineer here at MathWorks. See his earlier piece on solving Sudoku puzzles.
In this blog post we'll explore the fascinating world of continued fractions, like $ \sqrt{2} = 1 + \frac{1}{2 + \frac{1}{2 + \frac{1}{2 + \cdots}}} $. While these objects have been studied for several centuries, their presence in modern math classes is relatively rare (unless you're studying number theory, probably). One of the historical uses of these objects has been computing rational approximations of irrational numbers, such as the 5th century approximations for π of $ \frac{22}{7} $ and $ \frac{355}{113} $ by Chinese astronomer Zu Chongzhi. Here, we'll focus on something even less prevalent: their computational aspects. The goal is to start exploring statistical properties of continued fractions, generating conjectures, and then pointing to several topics that can serve as computational playgrounds to get one's hands dirty and explore even more.
Before defining what a continued fraction even is, we'll start by defining a few "important" numbers to use as examples throughout. Next we'll define continued fractions and compute some by hand, before introducing the computational algorithm to compute these things. Afterwards we'll explore their statistical properties, before discussing some conjectures and neat facts, and round out the discussion by including links to other interesting computational topics to explore.

Some Numbers

So that we have a rich class of examples, let's set up a few "important" numbers to use throughout the rest of this blog. Some of the numbers are important in some area(s) of math, though the whole collection should give us a nice, diverse set of examples to explore with. Also some of the names used are likely not standard, but describe how the numbers are constructed fairly well.
First, let's set up some parameters that'll determine the precision we'll be using throughout, along with a random number seed to ensure reproducibility no matter which machine (and when) these examples are run.
d = 10000; %set the computational precision "very" high
rng(1); %set the seed for the random number generator
And with that, let's set up our collection of numbers. For those interested in learning about each number, check out the code block at the end of this post. If you're content with knowing these are just being used as examples, feel free to skip seeing the definitions.
[num1, num2, num3, num4, num5, num6] = generateExamples(d);

Continued Fractions

So what exactly is a continued fraction? As the name implies, a continued fraction is a fraction that continues. What are fractions that don't continue? Most fractions you might think of, such as $ \frac{11}{13} $.
This isn't the only way to write this fraction though. One way, using Egyptian fractions, is $ \frac{11}{13} = \frac{1}{2} + \frac{1}{3} + \frac{1}{78} $, which we can verify using MATLAB's Symbolic Math Toolbox (which will also be used significantly later on):
eFrac = sym(1/2) + sym(1/3) + sym(1/78)
eFrac =

Another way is $ \frac{11}{13} = \frac{1}{1 + \frac{1}{ 5 + \frac{1}{2}}} $. We can check this just as we did above:
cFrac = 1/(1 + 1/(5 + sym(1/2)))
cFrac =

This is what we call a finite (simple) continued fraction: continued fraction because it continues, finite because there are finitely many terms, and simple because the numerators that appear are all 1. We also note that all of the coefficients we want should be positive integers; variations with negative integers also exist and the resulting continued fractions will have different properties.
This begs two natural questions:
  1. Are there continued fractions that have infinitely many terms?
  2. Are there continued fractions with numerators other than 1?
Yes and yes, which we'll demonstrate by example:
  1. The golden ratio $ \phi = \frac{1 + \sqrt{5}}{2} = 1+ \frac{1}{1 + \frac{1}{1 + \cdots}} \approx 1.618... $,
  2. $ \frac{4}{\pi} = 1 + \frac{1^2}{2 + \frac{3^2}{2 + \frac{5^2}{2 + \cdots}}} \approx 1.2732... $.
In this post we'll focus on infinite continued fractions, which we'll refer to as continued fractions for simplicity. Likewise, we won't touch on non-simple continued fractions, but rest assured they exist and often express interesting patterns and are fascinating mathematical objects to explore; for simplicity, whenever we say continued fraction we're talking about a simple continued fraction.
So how does one compute the continued fraction for a number? The general algorithm is a sort of Euclid's algorithm, wherein we take off the integer portion of a number, invert the fraction, and repeat. Let's see how this works with $ \frac{11}{13} $:
  1. $ \frac{11}{13} $ has no integer part, so we have $ \frac{11}{13} = 0 + \frac{11}{13} $.
  2. Next we invert the fractional part of the last expression, giving $ \frac{11}{13} = 0 + \frac{1}{\frac{13}{11}} $.
  3. For the newest "denominator", we repeat the process of taking out an integer part: since $ \frac{13}{11} = 1 + \frac{2}{11} $, we get $ \frac{11}{13} = 0 + \frac{1}{1 + \frac{2}{11}} $.
  4. Having isolated the integer part, we now invert the new fractional part $ \frac{2}{11} $, giving $ \frac{11}{13} = 0 + \frac{1}{1 + \frac{1}{\frac{11}{2}}} $.
  5. Since $ \frac{11}{2} = 5 + \frac{1}{2} $, we substitute this in to get the continued fraction $ \frac{11}{13} = 0 + \frac{1}{1 + \frac{1}{5 + \frac{1}{2}}} $.
It shouldn't be too surprising that any finite continued fraction corresponds to a rational number (just apply the algorithm backwards from the end of the continued fraction), but it may not be obvious that every rational number has a finite continued fraction. As a comparison, the decimal representation of $ \frac{1}{2} $ is $ 0.5 $, while the decimal representation of $ \frac{1}{3} $ is $ 0.333... $. It turns out that for continued fractions, there will be infinitely many coefficients if the number is irrational, and likewise if the number is irrational its continued fraction will have infinitely coefficients.

Infinite Continued Fractions

We've already seen one example of an infinite continued fraction, $ \phi = 1+ \frac{1}{1 + \frac{1}{1 + \cdots}} $. There are two ways to find the coefficients: one involves the algorithm from above, while the other leverages the fact that ϕ is a solution to $ 0 = \phi^2 - \phi - 1 $. Let's see both methods in action:
  1. Using the approximation $ \phi =1.618033988749895 $, we get $ \phi = 1 +0.618033988749895 $. Inverting the fraction gives $ \phi = 1 + \frac{1}{1.618033988749894} $, since $ \frac{1}{0.618033988749895} \approx 1.618033988749894 $. Notice that this new denominator is incredibly close to our original approximation for ϕ, and only differs in the last digit we've recorded. Continuing on, we get $ \phi = 1 + \frac{1}{1 + \frac{1}{\frac{1}{0.618033988749894}}} $, etc.
  2. The second method doesn't rely on approximations, but includes some of the observations in the last method. In particular, we saw that $ \frac{1}{\phi - 1} \approx \phi $, which upon rearranging gives $ 1 = \phi^2 - \phi $, which is precisely the equation $ 0 = \phi^2 - \phi - 1 $. What we'll do now is start with the quadratic equation for ϕ and rearrange it to get us the continued fraction fairly easily. So, starting with $ 0 = \phi^2 - \phi - 1 $, we rearrange to get $ \phi^2 = \phi + 1 $, and divide by ϕ to end up with $ \phi = \frac{\phi + 1}{\phi} $. Cleaning up the right-hand side of this last equality gives $ \phi = 1 + \frac{1}{\phi} $. What this expression suggests is that, since we have $ \phi = $ something, let's plug that something in to the left-hand side: $ \phi = 1+ \frac{1}{1 + \frac{1}{\phi}} $. Repeating this again gives $ \phi =1 + \frac{1}{1 + \frac{1}{1+\frac{1}{\phi}}} $, and so on.
This second method can be used for a lot of roots of quadratic equations, though for other irrational numbers there may or may not be some nice properties we can exploit. Before discussing how the general algorithm works in general, and implementing it in MATLAB, we'll see one more example of finding a continued fraction.
Let's find the continued fraction for $ \sqrt{2} $. First, recall that $ \sqrt{2} $ is a solution to the quadratic equation $ x^2 - 2 = 0 $. We can try to write this in the same form that worked for ϕ, namely $ x = \frac{2}{x} $, but this won't actually get us any closer. Instead, we're going to add 0 to $ \sqrt{2} $ and hope for the best: $ \sqrt{2} = \sqrt{2} + 1 - 1 = 1 + \left( \sqrt{2} - 1\right) $. This step is the first step of the general algorithm, since $ \sqrt{2} \approx 1.414 $, so we've successfully isolated the integer part. Next we invert the fractional part to get $ \frac{1}{\sqrt{2}-1} = \frac{\sqrt{2}+1}{(\sqrt{2}-1)(\sqrt{2}+1)} = \sqrt{2} + 1 $. Thus, our continued fraction should look like $ \sqrt{2} = 1 + \frac{1}{1 + \sqrt{2} } $. At this point we have the recurrence we need, and we can keep substituting $ \sqrt{2} $ back in on the left-hand side to get $ \sqrt{2} = 1 + \frac{1}{1 + 1 + \frac{1}{1 + \sqrt{2}} } = 1 + \frac{1}{2 + \frac{1}{1 + \sqrt{2}}} = 1 + \frac{1}{2 + \frac{1}{2 + \frac{1}{ 1 + \sqrt{2}}}} $, and so on.

Continued Fraction Notation

As you may have noticed, writing out a continued fraction can get fairly unwieldly. Since we're working with simple continued fractions, the only coefficients we have to keep track of are the "integer pieces" in each level of the continued fraction. For $ \sqrt{2} $ the integer piece is 1, but all of the subsequent coefficients are 2. So that we don't have to write out $ \sqrt{2} = 1 + \frac{1}{ 2 + \frac{1}{ 2 + \frac{1}{2 + \cdots} } } $ each time, we'll use the condensed notation $ \sqrt{2} = [1; 2,2,...] $. The semicolon just indicates that the first coefficient is "special" since it's the actual integer part. As another example, $ \phi =1 + \frac{1}{1 + \frac{1}{1+\frac{1}{1 + \cdots}}} = [1; 1, 1, ...] $.
As a third example, $ \pi = [3; 7, 15, 1, 292, 1, 1,...] = 3 + \frac{1}{7 + \frac{1}{15 + \frac{1}{1 + \frac{1}{292 + \frac{1}{1 + \cdots}}}}} $. Next, we'll implement the algorithm for computing continued fractions and verify this last representation.
More generally, if $ a_0, a_1, a_2, ... $ are positive integers, then the continued fraction $ a_0 + \frac{1}{a_1 + \frac{1}{a_2 + \cdots}} $ is written $ [a_0; a_1, a_2, ...] $.

Computing the Coefficients

As a quick reminder, the algorithm to find the coefficients for a continued fraction involves iteratively (1) taking out the integer part of a quantity, (2) inverting the fractional part, and repeating this indefinitely; in the case of using a computer, we repeat this process until our level of precision is met or exceeded. Let's see what this looks for ϕ and π.

Computing ϕ's Continued Fraction

As a test case to verify the algorithm, and its accuracy, we'll start with ϕ's continued fraction coefficients. Recall that $ \phi = [1; 1, 1, ...] $, so as soon as the algorithm returns a coefficient that is not 1, we'll know that's around the limitation of what we can accurately compute.
phi = vpa((1 + sqrt(sym(5)))/2,d) % define phi as a symbolic variable

phi = 

1.61803398874989484820458683436563811772030917980576286213544862270526046281890244970720720418939113748475408807538689175212663386222353693179318006076672635443338908659593958290563832266131992829026788067520876689250171169620703222104321626954862629631361443814975870122034080588795445474924618569536486444924104432077134494704956584678850987433944221254487706647809158846074998871240076521705751797883416625624940758906970400028121042762177111777805315317141011704666599146697987317613560067087480710131795236894275219484353056783002287856997829778347845878228911097625003026961561700250464338243776486102838312683303724292675263116533924731671112115881863851331620384005222165791286675294654906811317159934323597349498509040947621322298101726107059611645629909816290555208524790352406020172799747175342777592778625619432082750513121815628551222480939471234145170223735805772786160086883829523045926478780178899219902707769038953219681986151437803149974110692608867429622675756052317277752035361393621076738937645560606059216589466759551900400555908950229530942312482355212212415444006470340565734797663972394949946584578873039623090375033993856210242369025138680414577995698122445747178034173126453220416397232134044449487302315417676893752103068737880344170093954409627955898678723209512426893557309704509595684401755519881921802064052905518934947592600734852282101088194644544222318891319294689622002301443770269923007803085261180754519288770502109684249362713592518760777884665836150238913493333122310533923213624319263728910670503399282265263556209029798642472759772565508615487543574826471814145127000602389016207773224499435308899909501680328112194320481964387675863314798571911397815397807476150772211750826945863932045652098969855567814106968372884058746103378105444390943683583581381131168993855576975484149144534150912954070050194775486163075422641729394680367319805861833918328599130396072014455950449779212076124785645916160837059498786006970189409886400764436170933417270919143365013715766011480381430626238051432117348151005590134561011800790506381421527093085880928757034505078081454588199063361298279814117453392731208092897279222132980642946878242748740174505540677875708323731097591511776297844328474790817651809778726841611763250386121129143683437670235037111633072586988325871033632223810980901211019899176841491751233134015273384383723450093478604979294599158220125810459823092552872124137043614910205471855496118087642657651106054588147560443178479858453973128630162544876114852021706440411166076695059775783257039511087823082710647893902111569103927683845386333321565829659773103436032322545743637204124406408882673758433953679593123221343732099574988946995656473600729599983912881031974263125179714143201231127955189477817269141589117799195648125580018455065632952859859100090862180297756378925999164994642819302229355234667475932695165421402109136301819472270789012208728736170734864999815625547281137347987165695274890081443840532748378137824669174442296349147081570073525457070897726754693438226195468615331209533579238014609273510210119190218360675097308957528957746814229543394385493155339630380729169175846101460995055064803679304147236572039860073550760902317312501613204843583648177048481810991602442523271672190189334596378608787528701739359303013359011237102391712659047026349402830766876743638651327106280323174069317334482343564531850581353108549733350759966778712449058363675413289086240632456395357212524261170278028656043234942837301725574405837278267996031739364013287627701243679831144643694767053127249241047167001382478312865650649343418039004101780533950587724586655755229391582397084177298337282311525692609299594224000056062667867435792397245408481765197343626526894488855272027477874733598353672776140759171205132693448375299164998093602461784426757277679001919190703805220461232482391326104327191684512306023627893545432461769975753689041763650254785138246314658336383376023577899267298863216185839590363998183845827644912459809370430555596137973432613483049494968681089535696348281781288625364608420339465381944194571426668237183949183237090857485026656803989744066210536030640026081711266599541993687316094572288810920778822772036366844815325617284117690979266665522384688311371852991921631905201568631222820715599876468423552059285371757807656050367731309751912239738872246825805715974457404842987807352215984266766257807706201943040054255015831250301753409411719101929890384472503329880245014367968441694795954530459103138116218704567997866366174605957000344597011352518134600656553520347888117414994127482641521355677639403907103870881823380680335003804680017480822059109684420264464021877053401003180288166441530913939481564031928227854824145105031888251899700748622879421558957428202166570621880905780880503246769912972872103870736974064356674589202586565739785608595665341070359978320446336346485489497663885351045527298242290699848853696828046459745762651434359050938321243743333870516657149005907105670248879858043718151261004403814880407252440616429022478227152724112085065788838712493635106806365166743222327767755797399270376231914704732395512060705503992088442603708790843334261838413597078164829553714321961189503797714630007555975379570355227144931913217255644012830918050450089921870512118606933573153895935079030073672702331416532042340155374144268715405511647961143323024854404094069114561398730260395182816803448252543267385759005604320245372719291248645813334416985299391357478698957986439498023047116967157362283912018127312916589952759919220318372356827279385637331265479985912463275030060592567454979435088119295056854932593553187291418011364121874707526281068698301357605247194455932195535961045283031488391176930119658583431442489489856558425083410942950277197583352244291257364938075417113739243760143506829878493271299751228688196049835775158771780410697131966753477194792263651901633977128473907933611119140899830560336106098717178305543540356089529290818464143713929437813560482038947912574507707557510300242072662900180904229342494259060666141332287226980690145994511995478016399151412612525728280664331261657469388195106442167387180001100421848302580916543383749236411838885646851431500637319042951481469424314608952547072037405566913069220990804819452975110650464281054177552590951871318883591476599604131796020941530858553323877253802327276329773721431279682167162344211832018028814127474431688472184593927814354740999990722332030592629766112383279833169882539312620065037028844782866694044730794710476125586583752986236250999823233597155072338383324408152577819336426263043302658958170800451278873115935587747217256494700051636672577153920984095032745112153687300912199629522765913163709396860727134269262315475330437993316581107369643142171979434056391551210810813626268885697480680601169189417502722987415869917914534994624441940121978586013736608286907223651477139126874209665137875620591854328888341742920901563133283193575622089713765630978501563154982456445865424792935722828750608481453351352181729587932991171003247622205219464510536245051298843087134443950724426735146286179918323364598369637632722575691597239543830520866474742381511079273494836952396479268993698324917999502789500060459661313463363024949951480805329017902975182515875049007435187983511836032722772601717404535571658855578297291061958193517105548257930709100576358699019297217995168731175563144485648100220014254540554292734588371160209947945720823780436871894480563689182580244499631878342027491015335791072733625328906933474123802222011626277119308544850295419132004009998655666517756640953656197897818380451030356510131589458902871861086905893947136801484570018366495647203294334374298946427412551435905843484091954870152361403173913903616440198455051049121169792001201999605069949664030350863692903941007019450532016234872763232732449439630480890554251379723314751852070910250636859816795304818100739424531700238804759834323450414258431406361272109602282423378228090279765960777108493915174887316877713522390091171173509186006546200990249758527792542781659703834950580106261553336910937846597710529750223173074121778344189411845965861029801877874274456386696612772450384586052641510304089825777754474115332076407588167751497553804711629667771005876646159549677692705496239398570925507027406997814084312496536307186653371806058742242598165307052573834541577054292162998114917508611311765773172095615656478695474489271320608063545779462414531066983742113798168963823533304477883169339728728918103664083269856988254438516675862289930696434684897514840879039647604203610206021717394470263487633654393195229077383616738981178124248365578105034169451563626043003665743108476654877780128577923645418522447236171374229255841593135612866371670328072171553392646325730673063910854108868085742838588280602303341408550390973538726134511962926415995212789311354431460152730902553827104325966226743903745563612286139078319433570590038148700898661315398195857442330441970856696722293142730741384882788975588860799738704470203166834856941990965480298249319817657926829855629723010682777235162740783807431877827318211919695280051608791572128826337968231272562870001500182929757729993579094919640763442861575713544427898383040454702710194580042582021202344580630345033658147218549203679989972935353919681213319516537974539911149424445183033858841290401817818821376006659284941367754317451605409387110368715211640405821934471204482775960541694864539878326269548013915019038995931306703186616706637196402569286713887146631189192685682691995276457997718278759460961617218868109454651578869122410609814197268619255478789926315359472922825080542516906814010781796021885330762305563816316401922454503257656739259976517530801427160714308718862859836037465057134204670083432754230277047793311183666903232885306873879907135900740304907459889513647687608678443238248218930617570319563803230819719363567274196438726258706154330729637038127515170406005057594882723856345156390526577104264594760405569509598408889037620799566388017861855915944111725092313279771138
tempR = phi; % tempR is the number we have at the latest stage of the algorithm
numTerms = 100; % let's start with 1000 coefficients computed
%initialize an array of zeros so we have space allocated at the start for
%everything
A = zeros(1,numTerms);
%the main for loop where we compute the coefficients
for ii = 1:numTerms
%compute the integer piece of wherever we're at in the process
A(ii) = floor(tempR); % floor finds the nearest integer below tempR
%set up to get the next integer piece, etc.
tempR = 1/(tempR - floor(tempR)); % remove the integer piece and invert the fraction
end
% let's see what was computed
A
A = 1×100
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
The 96th coefficient is 2, not 1, so with this precision we're getting ~100 coefficients accurately. While this may not seem like too many coefficients, using the continued fraction with these 95 coefficients would let us compute ϕ to within about 40 digits. This follow's from Loch's theorem, since for ϕ it takes 2.39 continued fraction coefficients to approximate 1 digit of accuracy for ϕ.
Next, let's do the same with $ \pi = [3; 7, 15, 1, 292, 1, 1,...] $.
symPi = vpa(sym(pi),d)

symPi = 

3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198938095257201065485863278865936153381827968230301952035301852968995773622599413891249721775283479131515574857242454150695950829533116861727855889075098381754637464939319255060400927701671139009848824012858361603563707660104710181942955596198946767837449448255379774726847104047534646208046684259069491293313677028989152104752162056966024058038150193511253382430035587640247496473263914199272604269922796782354781636009341721641219924586315030286182974555706749838505494588586926995690927210797509302955321165344987202755960236480665499119881834797753566369807426542527862551818417574672890977772793800081647060016145249192173217214772350141441973568548161361157352552133475741849468438523323907394143334547762416862518983569485562099219222184272550254256887671790494601653466804988627232791786085784383827967976681454100953883786360950680064225125205117392984896084128488626945604241965285022210661186306744278622039194945047123713786960956364371917287467764657573962413890865832645995813390478027590099465764078951269468398352595709825822620522489407726719478268482601476990902640136394437455305068203496252451749399651431429809190659250937221696461515709858387410597885959772975498930161753928468138268683868942774155991855925245953959431049972524680845987273644695848653836736222626099124608051243884390451244136549762780797715691435997700129616089441694868555848406353422072225828488648158456028506016842739452267467678895252138522549954666727823986456596116354886230577456498035593634568174324112515076069479451096596094025228879710893145669136867228748940560101503308617928680920874760917824938589009714909675985261365549781893129784821682998948722658804857564014270477555132379641451523746234364542858444795265867821051141354735739523113427166102135969536231442952484937187110145765403590279934403742007310578539062198387447808478489683321445713868751943506430218453191048481005370614680674919278191197939952061419663428754440643745123718192179998391015919561814675142691239748940907186494231961567945208095146550225231603881930142093762137855956638937787083039069792077346722182562599661501421503068038447734549202605414665925201497442850732518666002132434088190710486331734649651453905796268561005508106658796998163574736384052571459102897064140110971206280439039759515677157700420337869936007230558763176359421873125147120532928191826186125867321579198414848829164470609575270695722091756711672291098169091528017350671274858322287183520935396572512108357915136988209144421006751033467110314126711136990865851639831501970165151168517143765761835155650884909989859982387345528331635507647918535893226185489632132933089857064204675259070915481416549859461637180270981994309924488957571282890592323326097299712084433573265489382391193259746366730583604142813883032038249037589852437441702913276561809377344403070746921120191302033038019762110110044929321516084244485963766983895228684783123552658213144957685726243344189303968642624341077322697802807318915441101044682325271620105265227211166039666557309254711055785376346682065310989652691862056476931257058635662018558100729360659876486117910453348850346113657686753249441668039626579787718556084552965412665408530614344431858676975145661406800700237877659134401712749470420562230538994561314071127000407854733269939081454664645880797270826683063432858785698305235808933065757406795457163775254202114955761581400250126228594130216471550979259230990796547376125517656751357517829666454779174501129961489030463994713296210734043751895735961458901938971311179042978285647503203198691514028708085990480109412147221317947647772622414254854540332157185306142288137585043063321751829798662237172159160771669254748738986654949450114654062843366393790039769265672146385306736096571209180763832716641627488880078692560290228472104031721186082041900042296617119637792133757511495950156604963186294726547364252308177036751590673502350728354056704038674351362222477158915049530984448933309634087807693259939780541934144737744184263129860809988868741326047215695162396586457302163159819319516735381297416772947867242292465436680098067692823828068996400482435403701416314965897940924323789690706977942236250822168895738379862300159377647165122893578601588161755782973523344604281512627203734314653197777416031990665541876397929334419521541341899485444734567383162499341913181480927777103863877343177207545654532207770921201905166096280490926360197598828161332316663652861932668633606273567630354477628035045077723554710585954870279081435624014517180624643626794561275318134078330336254232783944975382437205835311477119926063813346776879695970309833913077109870408591337464144282277263465947047458784778720192771528073176790770715721344473060570073349243693113835049316312840425121925651798069411352801314701304781643788518529092854520116583934196562134914341595625865865570552690496520985803385072242648293972858478316305777756068887644624824685792603953527734803048029005876075825104747091643961362676044925627420420832085661190625454337213153595845068772460290161876679524061634252257719542916299193064553779914037340432875262888963995879475729174642635745525407909145135711136941091193932519107602082520261879853188770584297259167781314969900901921169717372784768472686084900337702424291651300500516832336435038951702989392233451722013812806965011784408745196012122859937162313017114448464090389064495444006198690754851602632750529834918740786680881833851022833450850486082503930213321971551843063545500766828294930413776552793975175461395398468339363830474611996653858153842056853386218672523340283087112328278921250771262946322956398989893582116745627010218356462201349671518819097303811980049734072396103685406643193950979019069963955245300545058068550195673022921913933918568034490398205955100226353536192041994745538593810234395544959778377902374216172711172364343543947822181852862408514006660443325888569867054315470696574745855033232334210730154594051655379068662733379958511562578432298827372319898757141595781119635833005940873068121602876496286744604774649159950549737425626901049037781986835938146574126804925648798556145372347867330390468838343634655379498641927056387293174872332083760112302991136793862708943879936201629515413371424892830722012690147546684765357616477379467520049075715552781965362132392640616013635815590742202020318727760527721900556148425551879253034351398442532234157623361064250639049750086562710953591946589751413103482276930624743536325691607815478181152843667957061108615331504452127473924544945423682886061340841486377670096120715124914043027253860764823634143346235189757664521641376796903149501910857598442391986291642193994907236234646844117394032659184044378051333894525742399508296591228508555821572503107125701266830240292952522011872676756220415420516184163484756516999811614101002996078386909291603028840026910414079288621507842451670908700069928212066041837180653556725253256753286129104248776182582976515795984703562226293486003415872298053498965022629174878820273420922224533985626476691490556284250391275771028402799806636582548892648802545661017296702664076559042909945681506526530537182941270336931378517860904070866711496558343434769338578171138645587367812301458768712660348913909562009939361031029161615288138437909904231747336394804575931493140529763475748119356709110137751721008031559024853090669203767192203322909433467685142214477379393751703443661991040337511173547191855046449026365512816228824462575916333039107225383742182140883508657391771509682887478265699599574490661758344137522397096834080053559849175417381883999446974867626551658276584835884531427756879002909517028352971634456212964043523117600665101241200659755851276178583829204197484423608007193045761893234922927965019875187212726750798125547095890455635792122103334669749923563025494780249011419521238281530911407907386025152274299581807247162591668545133312394804947079119153267343028244186041426363954800044800267049624820179289647669758318327131425170296923488962766844032326092752496035799646925650493681836090032380929345958897069536534940603402166544375589004563288225054525564056448246515187547119621844396582533754388569094113031509526179378002974120766514793942590298969594699556576121865619673378623625612521632086286922210327488921865436480229678070576561514463204692790682120738837781423356282360896320806822246801224826117718589638140918390367367222088832151375560037279839400415297002878307667094447456013455641725437090697939612257142989467154357846878861444581231459357198492252847160504922124247014121478057345510500801908699603302763478708108175450119307141223390866393833952942578690507643100638351983438934159613185434754649556978103829309716465143840700707360411237359984345225161050702705623526601276484830840761183013052793205427462865403603674532865105706587488225698157936789766974220575059683440869735020141020672358502007245225632651341055924019027421624843914035998953539459094407046912091409387001264560016237428802109276457931065792295524988727584610126483699989225695968815920560010165525637568
tempR = symPi; % tempR is the number we have at the latest stage of the algorithm
numTerms = 100; % let's start with 100 coefficients computed
%initialize an array of zeros so we have space allocated at the start for
%everything
A = zeros(1,numTerms);
%the main for loop where we compute the coefficients
for ii = 1:numTerms
%compute the integer piece of wherever we're at in the process
A(ii) = floor(tempR); % floor finds the nearest integer below tempR
%set up to get the next integer piece, etc.
tempR = 1/(tempR - floor(tempR)); % remove the integer piece and invert the fraction
end
% let's see what was computed
A
A = 1×100
3 7 15 1 292 1 1 1 2 1 3 1 14 2 1 1 2 2 2 2 1 84 2 1 1 15 3 13 1 4 2 6 6 99 1 4 4 2 4 8 1 3 4 2 12 2 3 1 8 1
Just as expected! In case there's any doubt, the continued fraction coefficients for π can be externally verified using the Online Encyclopedia of Integer Sequences as A001203.
Since we'll use the algorithm over and over, it's been encoded in the function getCF available at the end of this post.
We can also visualize these coefficients using bar graphs, where the bars are only used a quick graphical aid to get a sense of the distribution, and in particular how large, the coefficients can get. Here we're using a higher precision than above since we're going to start going big with the number of coefficients we compute.
piCF = getCF(vpa(sym(pi),d),100);
% first 10 coefficients
bar(piCF(1:10))
title("First 10 continued fraction coefficients of \pi")
%first 100 coefficients
bar(piCF)
title("First 100 continued fraction coefficients of \pi")
Before getting to the core of this blog post - statistical properties of continued fraction coefficients - let's see what some of the other numbers we defined at the start of this post look like.
tic
num1CF = getCF(num1,100);
toc
Elapsed time is 0.133267 seconds.
bar(num1CF)
title("First 100 continued fraction coefficients of the Fibonacci constant")
tic
num2CF = getCF(num2,100);
toc
Elapsed time is 0.125300 seconds.
bar(num2CF)
title("First 100 continued fraction coefficients of Champernowne's constant")
tic
num3CF = getCF(num3,100);
toc
Elapsed time is 0.128072 seconds.
bar(num3CF)
title("First 100 continued fraction coefficients of the Prime constant")
tic
num4CF = getCF(num4,100);
toc
Elapsed time is 0.134937 seconds.
bar(num4CF)
title("First 100 continued fraction coefficients of the Squares constant")
tic
num5CF = getCF(num5,100);
toc
Elapsed time is 0.125739 seconds.
bar(num5CF)
title("First 100 continued fraction coefficients of Liouville's constant")
tic
num6CF = getCF(num6,100);
toc
Elapsed time is 0.123741 seconds.
bar(num6CF)
title("First 100 continued fraction coefficients of a random decimal")
Some of the coefficients get quite large, but most tend to stay closer (relatively speaking) to 1. While many of these coefficients may seem random, they have some pretty remarkable statistical properties as we'll explore next.

Statistics of the Coefficients

Since we've mentioned statistics, let's start by taking means of the coefficients and seeing what pops out. In particular, since we've been constructing continued fractions one coefficient at a time, we're going to take running means of the coefficients and see what their long-term behaviour is. Recall that the mean of numbers $ a_1, a_2, ..., a_n $ is $ \frac{a_1 + \cdots + a_n}{n} $.
We'll start by considering the running means of π's coefficients.
Means = zeros(1,100); % initialize an array to hold the means
for ii = 1:100
Means(ii) = mean(piCF(1:ii));
end
Means
Means = 1×100
3.0000 5.0000 8.3333 6.5000 63.6000 53.1667 45.7143 40.1250 35.8889 32.4000 29.7273 27.3333 26.3077 24.5714 23.0000 21.6250 20.4706 19.4444 18.5263 17.7000 16.9048 19.9545 19.1739 18.4167 17.7200 17.6154 17.0741 16.9286 16.3793 15.9667 15.5161 15.2188 14.9394 17.4118 16.9429 16.5833 16.2432 15.8684 15.5641 15.3750 15.0244 14.7381 14.4884 14.2045 14.1556 13.8913 13.6596 13.3958 13.2857 13.0400
Let's visualize these results with a line plot:
plot(Means)
The plot suggests that the means are tending towards the value 10, and inspecting the array of means tells us that the actual, apparent, limiting value is about 8. Let's do this same procedure for the other continued fractions we computed to use as examples and plot them all on the same graph.
Means = zeros(7,100); % initialize an array to hold the means
% this time 7 rows since we have pi and 6 other examples
% add the means for pi
for ii = 1:100
Means(1,ii) = mean(piCF(1:ii));
end
% add the means for the Fibonacci constant
for ii = 1:100
Means(2,ii) = mean(num1CF(1:ii));
end
% add the means for Champernowne's constant
for ii = 1:100
Means(3,ii) = mean(num2CF(1:ii));
end
% add the means for the Prime constant
for ii = 1:100
Means(4,ii) = mean(num3CF(1:ii));
end
% add the means for the Squares constant
for ii = 1:100
Means(5,ii) = mean(num4CF(1:ii));
end
% add the means for Liouville's constant
for ii = 1:100
Means(6,ii) = mean(num5CF(1:ii));
end
% add the means for random decimal
for ii = 1:100
Means(7,ii) = mean(num6CF(1:ii));
end
% plot all lines together
plot(Means')
ylim([0 100])
We can generate even more examples, and evidence for conjectures, by constructing more random decimals and plotting their running means.
numExperiments = 100; % the number of random numbers to generate
Means = zeros(numExperiments,100); % initialize an array to hold the means
tic % to time the computation
for jj = 1:numExperiments
%copying the code from above that generates a random decimal
tempDigits = randi(10,[1 d]) - 1; %generate an array of randomly selected digits between 1 to 9
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
randDec = vpa("0."+temp,d);
% compute its CF
randCF = getCF(randDec,100);
% compute its running means
for ii = 1:100
Means(jj,ii) = mean(randCF(1:ii));
end
end
toc % display how much time elapsed for the data generation
Elapsed time is 13.492355 seconds.
plot(Means')
ylim([0 100])
For most of the continued fractions, the means seem to tend to a value between 5 and 20, and all seem to be greater than 2.5. This is interesting, and with more coefficients we may generate more evidence for this observation - we may even generate a
Conjecture: the running means of (most) continued fractions coefficients is at least 2.5
(and prove it, later on).
Here though we'll pivot, and instead of exploring means, we'll explore geometric means of the coefficients. For numbers $ a_1, a_2, ..., a_n $, their geometric mean is the quantity $ (a_1a_2 \cdots a_n)^{1/n} $.
Let's start by computing the running geometric means of the continued fraction coefficients of π.
Geo = ones(1,99); % initialize the array to store geometric means
% we're taking 1 less than the size of the CF since we're ignoring the
% initial integer part
%the main for loop, where we loop through and compute the geometric means
%of the sequences
for ii = 2:length(piCF)
Geo(ii-1) = prod(nthroot(piCF(2:ii),ii)); %note the indexing
end
Geo
Geo = 1×99
2.6458 4.7177 3.2011 7.8943 5.5945 4.3746 3.6377 3.4037 3.0113 3.0103 2.7462 3.1127 3.0159 2.8019 2.6272 2.5854 2.5488 2.5164 2.4877 2.3821 2.8008 2.7601 2.6458 2.5448 2.7245 2.7342 2.8908 2.7869 2.8207 2.7895 2.8571 2.9221 3.2411 3.1340 3.1553 3.1756 3.1372 3.1568 3.2311 3.1399 3.1365 3.1543 3.1218 3.2167 3.1836 3.1796 3.1039 3.1644 3.0923 3.0246
plot(Geo)
The coefficients seem to converge to a value just below 3. Let's see what the other example numbers indicate.
Geo = ones(7,99); % initialize an array to hold the geometric means
% this time 7 rows since we have pi and 6 other examples
% add the geometric means for pi
for ii = 1:100
Geo(1,ii) = prod(nthroot(piCF(2:ii),ii));
end
% add the geometric means for the Fibonacci constant
for ii = 1:100
Geo(2,ii) = prod(nthroot(num1CF(2:ii),ii));
end
% add the geometric means for Champernowne's constant
for ii = 1:100
Geo(3,ii) = prod(nthroot(num2CF(2:ii),ii));
end
% add the geometric means for the Prime constant
for ii = 1:100
Geo(4,ii) = prod(nthroot(num3CF(2:ii),ii));
end
% add the geometric means for the Squares constant
for ii = 1:100
Geo(5,ii) = prod(nthroot(num4CF(2:ii),ii));
end
% add the geometric means for Liouville's constant
for ii = 1:100
Geo(6,ii) = prod(nthroot(num5CF(2:ii),ii));
end
% add the geometric means for random decimal
for ii = 1:100
Geo(7,ii) = prod(nthroot(num6CF(2:ii),ii));
end
% plot all lines together
plot(Geo')
ylim([0 10])
We can also run the same experiment as above, generating a bunch of random decimals and seeing what their running geometric means are.
numExperiments = 100; % the number of random numbers to generate
Geo = zeros(numExperiments,99); % initialize an array to hold the geometric means
tic % to time the computation
for jj = 1:numExperiments
%copying the code from above that generates a random decimal
tempDigits = randi(10,[1 d]) - 1; %generate an array of randomly selected digits between 1 to 9
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
randDec = vpa("0."+temp,d);
% compute its CF
randCF = getCF(randDec,100);
% compute its running geometric means
for ii = 2:100
Geo(jj,ii-1) = prod(nthroot(randCF(2:ii),ii));
end
end
toc % display how much time elapsed for the data generation
Elapsed time is 14.002318 seconds.
plot(Geo')
ylim([0 10])
Remarkably, the running geometric means tend towards a value between 2 and 3 much more noticeably than the running means did. Of course with more continued fraction coefficients we'd get more data, and hopefully stronger evidence, for a conjecture, like
Conjecture: the running geometric means of (most) continued fraction coefficients converge to 2.5.
The value 2.5 was chosen as the visual mean of the lines in our experiments. So the question remains: is our conjecture true?
Unfortunately it's not actually true. The actual value is $ \approx 2.68545... $
This result is known as Khinchin's constant, and was actually conjectured and proven in the 1930s. What's even wilder is the exact value is known, and is the infinite product$ \prod_{r=1}^\infty \left( 1 + \frac{1}{r(r+2)}\right)^{\log_2 r} $. The proof of this goes well beyond this post and involves more advanced mathematical techniques developed to study dynamical systems, but the linked Wikipedia article is a great starting point for intrepid explorers curious to learn more.
How does this connect to the exploration of means? Well, the AM-GM inequality tells us that the arithmetic mean (the usual mean) is always greater than or equal to the geometric mean of the same set of numbers. Since Khinchin's constant is what most running geometric means converge to, the running (arithmetic) means of continued fraction coefficients should converge to values greater than Khinchin's constant.

Other Topics to Explore

This discussion ignored many (arguably) more standard topics when it comes to continued fractions, like:
  1. convergents, or what you get when you truncate a continued fraction after finitely many terms,
  2. rates of convergence for convergents, or why $ \frac{22}{7} $ and $ \frac{355}{113} $ are excellent approximations of π,
  3. the fact that continued fractions are the "best" rational approximants for numbers,
  4. MATLAB's built-in rational approximation tools, which can find continued fractions with possibly negative exponents,
  5. Loch's theorem, which informs how many coefficients (or levels) of a continued fraction you need for another digit of accuracy (~1 coefficient per digit),
  6. how roots of quadratic polynomials have periodic continued fractions (the coefficients repeat), and are the only kinds of irrational numbers with periodic coefficients,
and so on. Indeed, when looking at convergents a result similar to Khinchin's constant exists called Levy's constant.
There even exist (non-simple) continued fraction expansions for some well-known functions, like
$ \sin(x) = \frac{x}{1 + \frac{x^2}{2\cdot 3 - x^2 + \frac{2\cdot 3 x^2}{4\cdot 5 - x^2 + \frac{4\cdot 5 x^2}{6\cdot 7 - x^2 + ...}} } } $. How this expression is obtained goes far beyond the discussion here, but hopefully serves as motivation to keep exploring these fascinating objects (the Wikipedia page on Euler's continued fraction might be a good starting point).
Happy exploring!
function [num1, num2, num3, num4, num5, num6] = generateExamples(d)
%%%%%%%%%%
%Number - Fibonacci's Constant
%0.1123581321..., constructed by concatenating the Fibonacci numbers 1, 1, 2, 3, 5...
numTerms = 70; %set the number of terms in the Fibonacci sequence to use
tempDigits = zeros(1,numTerms); %generate an empty array to store the first d terms of the Fibonacci sequence
tempDigits(1) = 1;%initialize the initial condition
tempDigits(2) = 1;%initialize the initial condition
%the main for loop where we fill in the Fib. sequence
for ii = 3:numTerms
tempDigits(ii) = tempDigits(ii-1) + tempDigits(ii-2);
end
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
num1 = vpa("0."+temp,d); % tell MATLAB to use Variable Precision Arithmetic (vpa) for high precision
%%%%%%%%%%
%Number 2 - Champernowne's Constant
%0.1234567891011..., constructed by concatenating the digits 1, 2, 3, ...
tempDigits = 1:d; %generate an array of the first d digits
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
num2 = vpa("0."+temp,d); % tell MATLAB to use Variable Precision Arithmetic (vpa) for high precision
%%%%%%%%%%
%Number 3 - Prime Constant
%0.235711..., formed by concatenating the prime numbers 2, 3, 5, 7, 11...
tempDigits = primes(d); %generate an array of the primes below d
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
num3 = vpa("0."+temp,d); % tell MATLAB to use Variable Precision Arithmetic (vpa) for high precision
%%%%%%%%%%
%Number 4 - Squares Concatenated Constant
%0.1491625..., formed by concatenating the integers squared 1, 4, 9, 16...
tempDigits = 1:d; %generate an array of the first d digits
tempDigits = tempDigits.^2; %square each of the terms in the array (hence the .^)
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
num4 = vpa("0."+temp,d); % tell MATLAB to use Variable Precision Arithmetic (vpa) for high precision
%%%%%%%%%%
%Number 5 - Liouville's Constant
%0.1100010000000000000000010... formed by adding a 1 in the decimal place and zeros elsewhere.
numTerms = 8; %number of factorial terms to use
LiouvilleIndeces = factorial(1:numTerms); %first identify where the ones should go
tempDigits = zeros(1,max(LiouvilleIndeces)+1); %generate an array of the first d digits
tempDigits(LiouvilleIndeces) = 1; %square each of the terms in the array (hence the .^)
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
num5 = vpa("0."+temp,d); % tell MATLAB to use Variable Precision Arithmetic (vpa) for high precision
%%%%%%%%%%
% Number 6 - Random Decimal
% A number whose decimal digits are all uniformly chosen between
tempDigits = randi(10,[1 d]) - 1; %generate an array of randomly selected digits between 1 to 9
temp = num2str(tempDigits); %convert the array to a string
temp = strrep(temp," ",""); %remove empty space in the string
num6 = vpa("0."+temp,d); % tell MATLAB to use Variable Precision Arithmetic (vpa) for high precision
end
function A = getCF(r,numTerms)
% get the continued fraction coefficients
%
% the input r is the number we want the CF of
% numTerms is however many coefficients we want to compute
%
tempR = r; % tempR is the number we have at the latest stage of the algorithm
% if numTerms isn't specified, default to computing 10 coefficients
if ~exist('numTerms','var')
numTerms = 10;
end
%initialize an array of zeros so we have space allocated at the start for
%everything
A = zeros(1,numTerms);
%the main for loop where we compute the coefficients
for ii = 1:numTerms
%compute the integer piece of wherever we're at in the process
A(ii) = floor(tempR);
%set up to get the next integer piece, etc.
tempR = 1/(tempR - floor(tempR)); % remove the integer piece and invert the fraction
end
end
]]>
What Is a Toolbox? New Guidelines for Authors https://blogs.mathworks.com/community/2023/06/21/what-is-a-toolbox-new-guidelines-for-authors/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/06/21/what-is-a-toolbox-new-guidelines-for-authors/#comments Wed, 21 Jun 2023 16:06:55 +0000 https://blogs.mathworks.com/community/?p=9392

The File Exchange provides access to more than 46,000 free MATLAB projects. For 33,854 of these projects, the authors included the word "toolbox" in the title. "Toolbox" is clearly a useful... read more >>

]]>
The File Exchange provides access to more than 46,000 free MATLAB projects. For 33,854 of these projects, the authors included the word "toolbox" in the title. "Toolbox" is clearly a useful designation in the MATLAB community! But what exactly IS a toolbox? It's always been a little vague. The closest thing we've had to a universal definition is this: a folder containing some related and potentially useful MATLAB files. This definition applies to everything from a sophisticated commercial product to a couple of modest utilities tossed into a folder. The salient point about a toolbox is that it is useful as an ensemble, perhaps only to you but probably to others as well. A toolbox is something that one might distribute.

Let's try to clarify things here. Consider the words project and toolbox. What is the difference?

A project is the entirety of the thing that you work on. These days, it often lives in a GitHub repository (so "project" and "repo" are sometimes used interchangeably). A toolbox is the thing you distribute to people who will then install and use it. So toolboxes derive from projects, but in general they aren't the same thing. A simple working project might be identical with its distributable toolbox. But as you add tests and other supporting material that won't ship with the toolbox, the project becomes the larger containing entity.

Here's how I sometimes picture it: the project is the garage and the toolbox is the car.

Now let me put on top of this picture some of the related words we use.

That's the basic idea of what a toolbox is. But let's zoom in a little. What should a modern standard toolbox look like?

For years we've been fielding requests about what constitutes a good toolbox. People want to know: How should I organize my toolbox code? How can I avoid the common pitfalls of distributing code? How can I encourage others to collaborate with me?

To answer these questions, we recently rolled out guidance on MATLAB Toolbox Best Practices. You can read all the details as published in this GitHub repo:

mathworks/toolboxdesign: Best practices for creating MATLAB toolboxes.

Or if you prefer, you can browse through this simple example instance of a standard toolbox, the Arithmetic Toolbox.

mathworks/arithmetic: Example toolbox created to showcase MATLAB Toolbox Best Practices.

Here is a short list of things we recommend.

  • use GitHub
  • include a README
  • make it a MATLAB Project
  • put all the "working code" into a toolbox/ subfolder
  • package with MLTBX files
  • create examples with Live Scripts (MLX files)
  • create tests that can be run using GitHub Actions

We don't claim you have to do all these things in order to be a good person. These are conventions that we recommend. If you follow this advice (or even just some of it), it will be easier for others to find and use your code. The tools you create will have more reach and more impact.

I'll close by observing that this is an early version of a living standard, so you can expect it to evolve over time. In fact, we hope you will help us evolve it by opening issues or participating in discussions. We hope it will be useful to you as you make and share tools in MATLAB.

]]>
https://blogs.mathworks.com/community/2023/06/21/what-is-a-toolbox-new-guidelines-for-authors/feed/ 1
Nine Insights from My Conversation with Heather Gorr, Senior MATLAB Product Manager https://blogs.mathworks.com/community/2023/05/31/nine-insights-from-my-conversation-with-heather-gorr/?s_tid=feedtopost Wed, 31 May 2023 16:43:26 +0000 https://blogs.mathworks.com/community/?p=9224

Today's guest article is by Hans Scharler. Live Interview on Discord Recently, I had the privilege of engaging in a captivating conversation with Heather Gorr, Ph.D., a senior MATLAB Product Manager... read more >>

]]>
Today's guest article is by Hans Scharler.

Live Interview on Discord

Recently, I had the privilege of engaging in a captivating conversation with Heather Gorr, Ph.D., a senior MATLAB Product Manager and Data Science expert at MathWorks. Our discussion covered a broad range of topics, from her daily work routine to her personal journey into the world of data science.

I held the interview live on the MATLAB Discord Server. I even kicked off the AMA with a Lex Fridman-inspired podcast introduction.

Today we're privileged to be joined by Heather, a force in the world of data science, a Senior MATLAB Product Manager at MathWorks. Trained as a materials science engineer and physicist, Heather's intellectual journey is one marked by a fierce hunger for knowledge and an inexhaustible curiosity that sees no boundaries. She has shown us that the path from the academic world to the tech industry isn't a straight line, but a beautiful winding road of discovery and continuous learning. Today, Heather stands not only at the edge of today's technological innovation, but also at the dawn of tomorrow's potential, creating a space where technology and human ingenuity dance in a never-before-seen ballet. As we dive into this conversation, remember that it is through the insights of brilliant minds like Heather's that we get a glimpse into the fascinating future that lies ahead of us.

Buckle up, and let's go on this remarkable journey together.

Here, I'll share nine insights that emerged from our conversation—each one offering a unique perspective on the field of data science and Heather's approach to her work.

1. Flexibility and Diversity in Roles

I asked Heather to describe one day from the past two weeks to give us some insight into what she may face on a typical day. Heather happened to choose the same day as the Discord AMA. Heather's description of that day reveals the diverse set of tasks and responsibilities that come with her role at MathWorks. From collaborating on a gorilla facial recognition project to hosting webinars and engaging in live streams, her role is dynamic and versatile, offering intellectual stimulation at every turn.

2. The Importance of Continuous Learning

Heather's drive to embrace a wide array of projects and tasks can be traced back to her insatiable curiosity and pursuit of knowledge. She puts an emphasis on continuous learning as it is a critical facet of the data science field, which is always evolving and expanding.

Why MathWorks? Teaching others, engaging with users, discovering cool stuff, and there's always something new to learn.

- Heather Gorr

3. The Journey of Career Discovery

Heather started studying physics, spent time in Nashville being a musician, and then found her passion in engineering and data science. This career journey serves as a reminder that career paths are not always straightforward—it's okay, and even beneficial, to take time to find what truly motivates and interests you. Heather now plays in a band and gigs out almost every weekend in New England.

4. The Value of Responding to Opportunities

Heather joined Mathworks in January 2013. An early but defining moment in her career was responding to a call to action. Someone at MathWorks needed help on a deep learning project and Heather volunteered to help out and apply her experience from her Ph.D. work. That someone turned out to be Cleve Moler, the creator of MATLAB. Heather's journey is all about responding to opportunities. Her response to Cleve Moler's call to action and the resulting projects, collaborations, and learning experiences illustrate the potential value of seizing opportunities. Being open to unexpected opportunities can lead to rewarding experiences that stretch far beyond your comfort zone.

5. The Role of Personal Experiences in Professional Growth

During the interview, Heather opened up about her dyslexia and ADHD and how she navigated academic and professional challenges providing an important perspective on the intersection of personal experiences and professional growth. Personal experiences, including the challenges we face, can shape our professional journey in significant ways. She felt it was important to share personal struggles and to be real about who we are.

6. The Balance of Technical Skills and Communication

Heather's role at MathWorks involves a mix of highly technical work, such as working on machine learning projects, and communication-focused tasks, such as teaching and hosting webinars. This balance underscores the importance of both technical expertise and communication skills in a data science role.

7. Applying Knowledge in Unique Ways

I asked Heather about a specific machine learning project that she worked on and she told us about a gorilla facial recognition project. What was fascinating about this project is that Heather was not trained specifically for this project, but she was prepared to handle it by applying her knowledge from other deep learning projects. Heather's work on the gorilla facial recognition project showcases the innovative applications of data science and machine learning and how important it is to work on diverse projects. You never know what you will be working on and how your experience will be impactful.

8. The Power of Collaboration

Heather frequently mentions collaborations in her work, such as her projects with Cleve Moler and others at MathWorks. She wanted to highlight the importance of collaborative work in data science, where different team members can bring unique perspectives and skills to solve complex problems.

9. Passion for Teaching and Sharing Knowledge

Heather made it clear that she loved teaching others. Her teaching experience and her enthusiasm for sharing her work through webinars and blog posts highlight her passion for education. It's a reminder of the importance of knowledge sharing and mentorship, which not only helps others learn but also fosters a strong, collaborative community.

Follow

My conversation with Heather Gorr not only shed light on her work and philosophy but also provided unique insights into the ever-evolving world of data science. Her journey, experiences, and perspectives have a lot to offer to anyone interested in the field. To follow Heather's work and contributions, you can find her on LinkedIn or visit her MathWorks community profile.

]]>
Solving Sudoku with MATLAB https://blogs.mathworks.com/community/2023/05/09/solving-sudoku-with-matlab/?s_tid=feedtopost Tue, 09 May 2023 17:15:15 +0000 https://blogs.mathworks.com/community/?p=9211

Today's guest article is by Wesley Hamilton, a STEM Outreach engineer here at MathWorks. Wesley's roles involve popularizing the use of MATLAB and Simulink for younger folk, especially towards... read more >>

]]>
Today's guest article is by Wesley Hamilton, a STEM Outreach engineer here at MathWorks. Wesley's roles involve popularizing the use of MATLAB and Simulink for younger folk, especially towards mathematical topics, and this blog is an accompanying piece to a workshop being run by the National Museum of Math in New York City.
Sudoku is a popular puzzle in which puzzlers fill in a 9x9 grid with the digits 1-9 such that a number of conditions are met: each 3x3 subgrid, row, and column must contain all digits. While Sudoku is usually referred to as a logic puzzle, it is actually possible to recast these puzzles as a (mathematical) constrainted optimization problem, wherein the optimal solution gets interpreted as the inputs for a completed Sudoku puzzle. What's crazy about this formulation though is that the function we optimize will be the zero function, so that any input is optimal; all of the legwork is in satisfying the optimization problem's constraints. Interested? Read on to learn more!
The presentation and code in this blog are adapted from a workshop developed by Dr. Tim Chartier, based on code developed in collaboration with Dr. Amy Langville of the College of Charleston and her students.

Rules and History of Sudoku

The classic version of Sudoku most people are familiar with consists of a 9x9 grid divided into nine 3x3 subgrids. The grid will start with some boxes filled in with the digits 1-9, and the goal of the puzzle is to fill in each box with one of the 9 digits in a way that the following three conditions are satisfied:
  1. Every row of the grid contains each of the digits 1-9, and each digit only appears once,
  2. Every column of the grid contains each of the digits 1-9, and each digit only appears once,
  3. Every 3x3 subgrid contains each of the digits 1-9, and each digit only appears once.
Here is an example of a 9x9 Sudoku puzzle, retrieved from websudoku.com on May 3, 2023.
sudoku_example.png
One variation of the puzzle is the 4x4 version, in which a 4x4 grid is split into four 2x2 subgrids and the three conditions are modified so that only the digits 1-4 are used. This version is often used as an easier version than the 9x9, and makes visualizing what happens in the computational side of things a bit more tractable as well.
Here is an example of a 4x4 Sudoku puzzle, generated by Dr. Tim Chartier, MoMath's 2022–2023 Distinguished Visiting Professor for the Public Dissemination of Mathematics.
sudoku_4x4_puzzle.png
Sudoku was popularized in Japan in the late 1980s, before grabbing worldwide attention in the early 2000s. Unbeknownst to many, very early versions of Sudoku appeared in France in the late 1800s as puzzle-variations of magic squares; see the Wikipedia page and its references for more information.
The next section walks through the basics of solving Sudoku puzzles. If you're already very familiar with Sudoku, feel free to skip down to the text right after the completed 4x4 puzzle.

Solving Sudoku Puzzles, part 1

So how does one solve a Sudoku puzzle? In practice, we iteratively apply the three conditions to identify which numbers go in which boxes until all boxes are filled in. In harder puzzles we may be forced to make a choice between two equally likely entries; in these situations we'll often try writing in one of the options and seeing what other numbers can get filled in based on that, and then either run into a contradiction, or solve the board.
Let's see this process in action with Tim's 4x4 puzzle. For clarity, the three conditions we'll be iteratively checking are:
  1. Every row of the grid contains each of the digits 1-4, and each digit only appears once,
  2. Every column of the grid contains each of the digits 1-4, and each digit only appears once,
  3. Every 2x2 subgrid contains each of the digits 1-4, and each digit only appears once.
First we'll focus on the upper-right 2x2 subgrid and identify where we may be able to fill in a number, in either the red circle or the blue square.
sudoku_4x4_puzzle_options_2.png
Applying condition 3., we know that the digits in these empty grid boxes have to be 2 and 3. So which digit goes where? By condition 2., each column of the grid can only contain each digit exactly once, and the fourth column (containing the blue square) already contains a 2, so it is not possible to write the digit 2 in the blue square (similarly, by condition 1. the row with the blue square already has the digit 2 somewhere in the row). Thus, the digit 2 goes in the square with the red circle.
sudoku_4x4_puzzle_first_write-in.png
Applying condition 3. to the same subgrid, we conclude the remaining grid box must contain the digit 3.
sudoku_4x4_puzzle_second_write-in.png
Continuing in this way we'll eventually be able to fill in every box; for example, the next move might be writing in the digit 4 in the only remaining box in the second row. Feel free to try solving this 4x4 on your own, and check your solution against ours:
sudoku_4x4_puzzle_solution.png
Awesome! But what if we want to have MATLAB solve the puzzle for us? An initial approach might be to code (in some way) these three constraints and have our computer iterate through each row, column, and subgrid writing in digits one-by-one. What happens if there are two digits that might work in a grid box? Are there other logical steps that might occur in a harder puzzle that we can't anticipate?
Instead of taking this approach, we'll take a very different, and possibly cleverer, approach making use of some deep and powerful computational mathematics known as Linear Programming.

Linear Programming

Linear programming is, simply put, an optimization problem in which the objective function and constraints are all linear. Let's break down what each of these pieces mean:
  • an optimization problem is a problem in which one seeks the maximum (or minimum) of an objective function, i.e. find a value for x that maximizes a given function $ f(x) $;
  • an objective function is the function we want to maximize or minimize. We could just call it a function, but often in optimization problems multiple functions come in to play, including functions that add constraints to the problem, in addition to the function we're optimizing;
  • a linear objective function is an objective function that is linear, i.e. takes the form $ f(x) = a_1 x_1 + \cdots + a_n x_n $, for a vector $ x = \pmatrix{x_1 \cr \vdots \cr x_n} $. Writing $ a = \pmatrix{a_1 \cr \vdots \cr a_n} $, this function can also be expressed $ f(x) = a^t x $, where the t superscript means we're taking the matrix transpose of a vector.
  • a constraint is a rule for which values of x are feasible, i.e. x must be non-negative, or if x is a vector then all of the components of x must be non-negative;
  • a linear constraint is a constraint that's written in the form of a linear equation. For example, if we're working with a vector $ x = \pmatrix{x_1 \cr x_2 \cr x_3} $, then a linear constraint might look like $ x_1 - x_2 + 3 x_3 \leq 0 $. If we write $ b=\pmatrix{1 \cr -1 \cr 3} $, then this linear constraint can also be written $ b^t x \leq 0 $, where the t superscript means we're taking the matrix transpose of a vector.
Linear constraints can actually come in two forms: linear inequalities ($ Ax\leq b $) and linear equalities ($ A_{eq} x = b_{eq} $). Both kinds of constraints The kinds of linear programs we'll work with here can all be expressed in the following form:
find a vector x that maximizes $ f(x) = a^t x $ subject to $ Ax \leq b $, $ A_{eq} x = b_{eq} $, and $ x\geq 0 $,
where $ a, b, b_{eq} $ are given vectors, and $ A, A_{eq} $ are given matrices encoding the linear constraints. Note that if $ x = \pmatrix{x_1 \cr \vdots \cr x_n} $, then the notation $ x\geq 0 $ means $ x_i \geq 0 $ for $ i=1, ..., n $. The components $ x_i $ of the vector x are often called decision variables, since these are the values the linear program needs to decide, or find values for.
In this post we'll be using MATLAB's intlinprog function, which you can treat as a black box linear program solver that finds integer solutions to a linear program. This solver automatically selects which algorithm to use and works to find a solution, so the only work we have to do is write down the linear program in a way it can understand. We'll do that next.
Keep in mind that we're using a matrix multiplication formulation to express the constraints. For background on matrix multiplication and basic linear algebra concepts, check out our interactive courseware module on Matrix Methods of Linear Algebra.

Sudoku as a Linear Program

To set up a Sudoku puzzle as a linear program, we need to identify a few things:
  1. What are the variables that we're solving for?
  2. What are the constraints we want to impose?
  3. What is the function we want to maximize?
Why not identify the function before the constraints? Well, turns out we don't actually care what the function is, which will be clear by the end of this section.
So what should the variables be? For a 4x4 grid we have 16 total boxes to fill in, and an initial approach might be to use variables $ x_1, ..., x_{16} $ where each $ x_i $ should take a value between 1 and 4. While reasonable, there's actually a computationally easier approach.
Instead of using the variables to tell us which digit is in each box, let's use variables to tell us whether or not a digit is in a box. By this we mean using variables $ x_{ijk} $, where the pair $ (i,j) $ tells us which box we're looking at, and k specifies which digit we care about. If $ x_{ijk} = 0 $, then digit k should not be written in box $ (i,j) $, while if $ x_{ijk} = 1 $, then digit k belongs in box $ (i,j) $.
As an example, consider the 4x4 grid we considered earlier (with some of the box indeces added in the top-left corners for clarity):
sudoku_4x4_puzzle_first_write-in_box_idx.png
To number the grid boxes, $ (1,1) $ will be the top-left box, $ (2,1) $ will be the box beneath it, and $ (1,2) $ will be the box to the right of $ (1,1) $. In other words, the first index i in $ (i,j) $ counts how many rows down we go, and the index j counts how many columns to the right we go.
So with this notation, we have the digit 4 in the $ (1,4) $ box, the digit 1 in the $ (2,3) $ box, and the digit 2 in the $ (3,4) $ box at the start (among others). In particular, the digits $ 1,2,3 $ do not appear in the $ (1,4) $ box. Using our variables to encode this information, we'd have $ x_{1,4,4}=1 $ and $ x_{1,4,1} = x_{1,4,2} = x_{1,4,3} = 0 $. At the start of the puzzle we did not know which digit went in the $ (1,3) $ box, so at the start $ x_{1,3,k} $ is not specified for $ k=1,...,4 $. Using the rules of Sudoku, we identified that a 2 belongs in that box, so by using the constraints we concluded that $ x_{1,3,2} = 1 $ and $ x_{1,3,1}=x_{1,3,3} = x_{1,3,4} = 0 $. Now that we have our variables specified, we're in a position to specify the constraints.
So how do we encode the Sudoku constraints into this framework? Keep in mind there are three constraints from the original puzzle which we'll need to encode in turn. There's actually a fourth constraint we need to encode, as discussed just above, in which each box can only have a single digit written in it.

Box constraints

The first constraint we need to encode is that each box can only have one digit written in it. So, for the $ (i,j) $ box, as soon as the digit 1 is written in it (for example), we get $ x_{i,j,1} = 1 $ and $ x_{i,j,2} = x_{i,j,3} = x_{i,j,4} = 0 $. The trick here is that each variable should take the value of either 0 or 1 (and nothing else), so if we sum them up and set the sum equal to 1, that ensures only one of the variables can take the value 1. Written out explicitly, for each of the boxes $ (i,j) $ we require:
$ x_{i,j,1} + x_{i,j,2} + x_{i,j,3} + x_{i,j,4} = 1 $.

Row constraints

The first of the puzzle constraints is that each row of the grid has each of the digits, and that each digit only appears once. Since we're looking at the rows, we're going to be focusing on sets of variables $ x_{i,1,k}, x_{i,2,k}, x_{i,3,k}, x_{i,4,k} $ for $ i = 1,...,4 $ and $ k=1,...,4 $. The trick here is the same as above, in that each variable should take the value of either 0 or 1 (and nothing else), so if we sum them up then, in a solved puzzle, we should get exactly 1:
$ x_{i,1,k} + x_{i,2,k} + x_{i,3,k} + x_{i,4,k} = 1 $.
As soon as one of the $ x_{i,j,k} $ takes the value 1, the rest are forced to be 0. This ensures that, in the ith row, the digit k only appears once. This constraint should hold for every possible row i and possible digit k.

Column constraints

The column constraint is set up exactly the same way as the row constraint, except here we're summing over the row indeces instead of the column indeces:
$ x_{1,j,k} + x_{2,j,k} + x_{3,j,k} + x_{4,j,k} = 1 $,
and this equality should hold for every possible column j and digit k.

Subgrid constraints

The last of the Sudoku puzzle constraints to implement is the subgrid rule, in which each of the four digits is present in each of the 2x2 subgrids. As a specific example to guide our work, consider the subgrid in the top-left consisting of the boxes $ (1,1), (1,2), (2,1), (2,2) $. The subgrid constraint specifies that each digit k appears just once among these four boxes, so we'll actually have four constraints for this subgrid:
$ x_{1,1,k} + x_{1,2,k} + x_{2,1,k} + x_{2,2,k} = 1 $, $ k=1,...,4 $.
There are four of these subgrids though, so we also need to incorporate those constraints:
$ x_{1,3,k} + x_{1,4,k} + x_{2,3,k} + x_{2,4,k} = 1 $, $ k=1,...,4 $,
$ x_{3,1,k} + x_{3,2,k} + x_{4,1,k} + x_{4,2,k} = 1 $, $ k=1,...,4 $,
$ x_{3,3,k} + x_{3,4,k} + x_{4,3,k} + x_{4,4,k} = 1 $, $ k=1,...,4 $.
That's a lot! Good thing we don't have to work with all of these equations by hand and have MATLAB to do all the heavy lifting for us!
The last thing we need to do is specify what our objective function is, the thing we're actually minimizing. The thing is, though, we've already encoded everything we want to keep track of through the variables and constraints, so there isn't any need for a specific function. This means that, for our purposes, we're free to set the function to be $ f(x) = 0 $. In this case, any vector x maximizes the function, so all of the work goes into finding a vector x that satisfies the constraints. If this still seems weird, you're not alone; if it helps, you're welcome to just have faith that we'll get a solution using this weird function, that's perfectly fine.
To summarize our work in this section, we're solving the following linear program:
find a vector $ x = \pmatrix{x_{1,1,1}\cr x_{1,1,2}\cr \vdots \cr x_{4,4,4}} $ that maximizes the function $ f(x) = 0 $, subject to the constraints
  • $ x_{i,j,1} + x_{i,j,2} + x_{i,j,3} + x_{i,j,4} = 1 $ for $ i = 1,...,4 $ and $ j=1,...,4 $, (box constraint)
  • $ x_{i,1,k} + x_{i,2,k} + x_{i,3,k} + x_{i,4,k} = 1 $ for $ i = 1,...,4 $ and $ k=1,...,4 $, (row constraint)
  • $ x_{1,j,k} + x_{2,j,k} + x_{3,j,k} + x_{4,j,k} = 1 $ for $ j = 1,...,4 $ and $ k=1,...,4 $, (column constraint)
  • $ x_{1,1,k} + x_{1,2,k} + x_{2,1,k} + x_{2,2,k} = 1 $ for $ k=1,...,4 $, (top-left subgrid constraint)
  • $ x_{1,3,k} + x_{1,4,k} + x_{2,3,k} + x_{2,4,k} = 1 $ for $ k=1,...,4 $, (top-right subgrid constraint)
  • $ x_{3,1,k} + x_{3,2,k} + x_{4,1,k} + x_{4,2,k} = 1 $ for $ k=1,...,4 $, (bottom-left subgrid constraint)
  • $ x_{3,3,k} + x_{3,4,k} + x_{4,3,k} + x_{4,4,k} = 1 $ for $ k=1,...,4 $. (bottom-right subgrid constraint)
Note that all of this work was just for the 4x4 version of Sudoku; how would we modify everything for the original 9x9 version? Take a minute to think about it, and then read on for a solution... Afterwards we'll implement everything in MATLAB and actually solve some puzzles.
For the 9x9 version, the straightforward changes are that the sums should include 9 terms everywhere, and the indeces $ i,j,k $ should each range from 1 to 9 everywhere. The more-involved modification is that there will be nine subgrid constraints instead of four, since the 9x9 grid contains nine 3x3 subgrids. The top-left 3x3 subgrid will have the constraint
$ x_{1,1,k} + x_{1,2,k} + x_{1,3,k} + x_{2,1,k} + x_{2,2,k} + x_{2,3,k} + x_{3,1,k} + x_{3,2,k} + x_{3,3,k} = 1 $, for $ k = 1, ..., 9 $.
The other subgrid constraints can be written out in a similar (slightly cumbersome) way.

Solving Sudoku Puzzles, part 2

In this section, we'll encode the constraints we described above and actually solve a Sudoku puzzle using linear programming.
There's one other set of constraints that we need to impose, that are independent of our framework and the rules of Sudoku. Remember that a Sudoku puzzle starts with some of the grid boxes filled in, which we can specify by a matrix G specifying the row number, column number, and digit of each of the initial entries. As a concrete example, for our 4x4 example we have $ G = \pmatrix{1 & 4 & 4 \cr 2 & 1 & 2\cr 2 & 3 & 1\cr 3 & 1 & 3 \cr 3 & 4 & 2} $; the first row is $ (1\, 4\, 4) $ since we start with the digit 4 in the first row and fourth column, etc.
The first thing to do is specify the size of the Sudoku grid where working with:
n=4; % for 4 by 4 sudoku problem
%n=9;  % for 9 by 9 sudoku problem

Ordering of decision variables

Keep in mind that the vector of variables, specifying which digits appear where in the grid, will have $ n^3 $ entries: $ n\times n $ entries corresponding to each box in the grid, and another n for the n possible digits. One thing we need to be careful about is what order our decision variables appear in our vector. Three (plus one) reasonable options are:
  1. Order the variables by incrementing the digit index first, then the column index, then the row index: $ x_{1,1,1}, x_{1,1,2}, ..., x_{1,1,4}, x_{1,2,1}, x_{1,2,2}, ... $ This enumeration will list all the digit design variables first before going to a new box.
  2. Order the variables by incrementing the row index first, then the column index, then the digit index: $ x_{1,1,1}, x_{2,1,1}, ..., x_{4,1,1}, x_{1,2,1}, x_{2,2,1}, ... $ This enumeration will iterate through the entire grid by going down columns then across rows, before increment the digit index and iterating through again.
  3. Order the variables by incrementing the column index first, then the row index, then the digit index: $ x_{1,1,1}, x_{1,2,1}, ..., x_{1,4,1}, x_{2,1,1}, x_{2,2,1}, ... $ This is similar to the previous possible enumeration, except we traverse the grid along rows first, then along columns, then along digits.
  4. Order the variables randomly.
The fourth option isn't actually reasonable, since you'll have significantly more bookkeeping to manage (it is, technically, possible to implement though!). Here we'll take option two, so that every set of $ n^2 $ components of the decision vector x correspond to the same digit enumerated along columns and then rows.
Namely, for our implementation here, x(1) tells us whether or not digit 1 is in the $ (1,1) $ box, x(n^2+1) tells us if the digit 2 is in the $ (1,1) $ box, etc. Likewise, x(2) tells us if the digit 1 is in the $ (2,1) $ box, x(3) tells us if the digit 1 is in the $ (3,1) $ box, x(n^2+2) tells us if the digit 2 is in the $ (2,1) $ box, etc.
Extra Challenge: implement this Sudoku solver using the other two (reasonable) methods of ordering the design variables. Extra bonus points for implementing the random ordering approach.
Next let's encode the constraints as a matrix $ A_{eq} $, so that in our linear program we'll have $ A_{eq} x = b $ as our constraint. The matrix $ A_{eq} $ should be a $ C\times n^3 $ matrix, where C is the number of constraints. The vector b will be a vector of 1s, being the right-hand side of each of our constraints.
What is C in this case? The constraints we identified are:
  • for each of the $ n^2 $ grid boxes we have a single constraint, totalling $ n^2 $ constraints,
  • for each of the n rows, and each of the n digits, we have a constraint, totalling $ n^2 $ constraints,
  • for each of the n columns, and each of the n digits, we have a constraint, totalling $ n^2 $ constraints,
  • for each of the n subgrids, we have n constraints telling us each digit must appear in that subgrid, totalling $ n^2 $ constraints,
  • we start with $ |G| = \# $of rows of G entries already filled in, totalling $ |G| $ constraints.
Summing these numbers up, we get $ C = 4n^2 + G $. In our approach, we'll define $ A_{eq} $ with $ C = 4n^2 $ first and fill in the first four constraints in the above bulleted list. Once finished, we'll add $ |G| $ more rows to $ A_{eq} $ and incorporate the givens. So let's start by initializing $ A_{eq} $:
Aeq=zeros(4*n^2, n^3);
Here's a sketch of the matrix we'll be filling in during the rest of this section:
sudoku_matrix_init.png
At the top we've indicated how the decision variables are ordered: the first $ n^2 $ columns correspond to whether or not digit 1 is written in the boxes $ (1,1), (2,1), ..., (n,n) $, the next $ n^2 $ columns correspond to digit 2, and so on, exactly as we specified when we decided to use option 2 for ordering above. The rows are split based on the constraints we're encoding as well as the given entries of the initial Sudoku puzzle.
In the next few subsections we'll iterate through this matrix and write-in each of constraints. The subsections showcase what the matrix will look like (i.e. where the 0's and 1's go), before displaying the MATLAB code that accomplishes this (with plenty of comments).

Box constraints

sudoku_matrix_box_constraints.png
%% Fill in Aeq for the n^2 constraints requiring that each element
%  of the matrix must contain an integer 1:n
for i=1:n % for each row (of the Sudoku grid)
    for j=1:n % for each column (of the Sudoku grid)
        for k=1:n % increment through each digit
          % the (i,j) grid box is associated to row (i-1)*n+j of A_eq
          % incrementing the digit k comes with n^2 entries along the array
          % though the box index (i,j) stays the same as we incorporate all
          % digits
          Aeq((i-1)*n+j,(i-1)*n+j + (k-1)*n^2)=1;
        end
    end
end
% if we had ordered the design variables so that we increment through
% digits first, we could replace this code with
%
% for i=1:n^2
% Aeq(i,(i-1)*n+1:i*n)=ones(1,n);
% end

Row constraints

sudoku_matrix_row_constraints.png
%% Fill in Aeq for the n^2 constraints requiring that each row
%  can have only 1 of each integer 1:n
for k=1:n % for each digit
    for i=1:n % fix the row of the Sudoku grid
        for j=1:n % increment the column indeces we're summing up
            % note that we've already added the n^2 box constraints
            % so updating A_eq starts at the n^2 row
            Aeq(n^2+i+(k-1)*n,1+(i-1)+(j-1)*n+(k-1)*n^2)=1;
        end
    end
end
% if we had ordered the design variables so that we increment through
% rows first, we could replace this code with
%
% for i=1:n^2
% Aeq(n^2+i,(i-1)*n+1:i*n)=ones(1,n);
% end

Column constraints

sudoku_matrix_column_constraints.png
%% Fill in Aeq for the n^2 constraints requiring that each column
%  can have only 1 of each integer 1:n
for i=1:n^2 % quick trick since the column constraints correspond to rows of adjacent 1s
    % we've added the n^2 box constraints and n^2 row constraints
    % so these constraints start on row 2*n^2
    % since our variable indexing goes along columns first,
    % when incorporating these constraints  
    Aeq(2*n^2 + i,(i-1)*n+1:i*n)=ones(1,n);
end

Subgrid constraints

sudoku_matrix_subgrid_constraints.png
%% Fill in Aeq for the n^2 constraints requiring that each submatrix
%  can have only 1 of each integer 1:n
% note that n is a square, so sqrt(n) is an integer
% m and l are indeces for the subgrids - m=1, l=1 is the top-left subgrid
for m=1:sqrt(n)
    for l=1:sqrt(n) % for the (m,l) subgrid
        for j=1:n
            for k=1:sqrt(n)
              % added n^2 box, n^2 row, and n^2 column constraints
              % the subgrid constraints should be added starting at row 3*n^2
              Aeq(3*n^2+(m-1)*sqrt(n)*n+(l-1)*n+j,(j-1)*n^2+(l-1)*sqrt(n)+...
                (m-1)*sqrt(n)*n+(k-1)*n+1:...
                (j-1)*n^2+(l-1)*sqrt(n)+(m-1)*sqrt(n)*n+(k-1)*n+sqrt(n))=1;
            end
        end
    end
end

The givens

Next, we need to incorporate the information that some of the entries are already filled in. We'll do this by specifying the givens in the form of the matrix mentioned at the start of this section, and then writing this information into $ A_{eq} $ in newly added rows below the information we've already incorporated.
For this example, we'll use the same matrix G for our favourite 4x4 example:
% If any values of the Sudoku matrix are given, add these as
%  constraints
% Enter each given value in matrix as triplet (row, col, integer)
% Example for 4-by-4 sudoku
Givens=[1 4 4;
        2 1 2;
        2 3 1;
        3 1 3;
        3 4 2];
With this matrix specified, let's now append rows to $ A_{eq} $ and incorporate these constraints specifying our given digits:
% turn these given elements into their appropriate position in the x vector
% of decision variables.
g=size(Givens,1);
for i=1:g % for each of the givens
    % we've added in 4*n^2 constraints already, so the first of the givens
    % should be added at row 4*n^2 + 1, etc.
    % the column entry to write the given constraint is at
    % rowId + colId*n + digitId*n^2
    % based on how we've organized the decision variables
    Aeq(4*n^2+i,Givens(i,1)+(Givens(i,2)-1)*n+(Givens(i,3)-1)*n^2)=1;
end
This concludes writing out $ A_{eq} $. The final matrix should resemble this sketch:
sudoku_matrix_givens.png
Note the 1 at the matrix element corresponding to the given $ (2,1,2) $.
Since all of the constraints are set-up to equal 1, the vector b in $ A_{eq}x = b $ should be a vector of 1s:
beq=ones(4*n^2+g,1);
With the variables and constraints in place, we're almost ready to have MATLAB generate our solution. Looking at the documentation for intlinprog, we need to explicitly specify some other pieces:
  • intcon, or the variables in x that should be integers. We want all of the components of x to be integers, so this should be the array 1:numVariables,
  • numVariables, or the length of the variable x ($ n^3 $ in this case),
  • lb, the vector of lower bounds for each of the variables. Since each $ x_{ijk} $ is 0 or 1, lb will be a vector of 0s,
  • ub, the vector of upper bounds for each of the variables. Since each $ x_{ijk} $ is 0 or 1, ub will be a vector of 1s.
Let's go ahead and specify each of these variables:
%% run matlab's "intlinprog" command
numVariables = size(Aeq,2);
intcon = 1:numVariables;
lb = zeros(1,numVariables);
ub = ones(1,numVariables);
With everything in place, let's generate a solution to our 4x4 puzzle.
[x,fval,exitflag,output]=intlinprog(zeros(n^3,1),intcon,[],[],Aeq,beq,lb,ub);

LP: Optimal objective value is 0.000000.

Optimal solution found.

Intlinprog stopped at the root node because the objective value is within a gap tolerance of the optimal value,
options.AbsoluteGapTolerance = 0 (the default value). The intcon variables are integer within tolerance,
options.IntegerTolerance = 1e-05 (the default value).

% note the two arguments of []
% these inputs correspond to inequality constraints
% since we're not using inequality constraints, we leave these inputs empty
exitflag;
output;
x
x = 64×1
1
0
0
0
0
0
1
0
0
1
For our 4x4 example, x is a vector with $ 4^3 = 64 $ entries, each of which is 0 or 1. While this is a solution to the linear program, it's not yet helpful for our purposes; what would be nice is if we could convert this vector into a grid of digits 1 to 4, corresponding to a Sudoku solution. Let's do that now and see the result:
%% turn matlab's outputed solution vector x into sudoku terms
S=zeros(n,n); %initialize the grid of solutions
for k=1:n % for each digit
  % find the entries in the solutions vector x corresponding to digit k
  % that have a value of 1 (i.e., the digit should be written in that box)
  subx=find(x((k-1)*n^2+1:k*n^2));
  for j=1:n % loop through
      row=mod(subx(j),n);
      if row==0
          row=n;
      end
      S(row,j)=k;
  end
end
% Sudoku Matrix S
S
S = 4×4
1 3 2 4
2 4 1 3
3 1 4 2
4 2 3 1
Compare this to the solution we generated by hand earlier, and see that MATLAB succeeded in finding the same solution!
sudoku_4x4_puzzle_solution.png
Next up is to try this with your own puzzles. The code has been copied below in one section for your convenience, with the sample 9x9 puzzle shown at the start encoded in the given matrix. Check that MATLAB can solve that as well, and try your own!

Further directions

Interested in exploring some other interesting questions related to this post? Here are some further directions to get you started:
  1. What happens if we don't add any givens to the linear program, i.e. we start with an empty Sudoku board? We should end up with a solution - is it unique? How might we interpret this solution? (The solver may take a bit longer to find the solution, but it will find a solution.)
  2. How might you impose other constraints to transform the Sudoku puzzle into something possibly more difficult? Two options might be: (a) requiring that each diagonal of the Sudoku grid contains each of the digits 1-9 once and only once, and (b) requiring that the middle boxes of each subgrid form their own subgrid requiring each of the digits 1-9 once and only once.
  3. Pick another variant of Sudoku and implement those constraints, such as if the subgrids are shaped differently.

Just the code

%n=4;  % for 4 by 4 sudoku problem
n=9; % for 9 by 9 sudoku problem
Aeq=zeros(4*n^2, n^3);
%% Fill in Aeq for the n^2 constraints requiring that each element
%  of the matrix must contain an integer 1:n
for i=1:n
    for j=1:n
        for k=1:n
          Aeq((i-1)*n+j,(i-1)*n+j + (k-1)*n^2)=1;
        end
    end
end
%% Fill in Aeq for the n^2 constraints requiring that each row
%  can have only 1 of each integer 1:n
for k=1:n
    for i=1:n
        for j=1:n
            Aeq(n^2+i+(k-1)*n,1+(i-1)+(j-1)*n+(k-1)*n^2)=1;
        end
    end
end
%% Fill in Aeq for the n^2 constraints requiring that each column
%  can have only 1 of each integer 1:n
for i=1:n^2
    Aeq(2*n^2+i,(i-1)*n+1:i*n)=ones(1,n);
end
%% Fill in Aeq for the n^2 constraints requiring that each submatrix
%  can have only 1 of each integer 1:n
for m=1:sqrt(n)
    for l=1:sqrt(n)
        for j=1:n
            for k=1:sqrt(n)
              Aeq(3*n^2+(m-1)*sqrt(n)*n+(l-1)*n+j,(j-1)*n^2+(l-1)*sqrt(n)+...
                (m-1)*sqrt(n)*n+(k-1)*n+1:...
                (j-1)*n^2+(l-1)*sqrt(n)+(m-1)*sqrt(n)*n+(k-1)*n+sqrt(n))=1;
            end
        end
    end
end
% If any values of the Sudoku matrix are given, add these as
%  constraints
% Enter each given value in matrix as triplet (row, col, integer)
% Example for 9-by-9 sudoku
Givens=[1 1 4;
        1 2 9;
        1 6 5;
        1 9 1;
        2 2 5;
        2 7 7;
        2 8 2;
        2 9 9;
        3 3 2;
        3 6 8;
        3 8 4;
        3 9 5;
        4 1 2;
        4 3 8;
        4 5 4;
        4 6 3;
        5 2 7;
        5 4 8;
        5 6 6;
        5 8 3;
        6 4 5;
        6 5 9;
        6 7 1;
        6 9 8;
        7 1 7;
        7 2 8;
        7 4 6;
        7 7 4;
        8 1 3;
        8 2 4;
        8 3 9;
        8 8 6;
        9 1 5;
        9 4 3;
        9 8 1;
        9 9 7];
% turn these given elements into their appropriate position in the x vector
% of decision variables.
g=size(Givens,1);
for i=1:g
    Aeq(4*n^2+i,Givens(i,1)+(Givens(i,2)-1)*n+(Givens(i,3)-1)*n^2)=1;
end
% beq=rhs vector (3n^2 by 1) for equality contraints
beq=ones(4*n^2+g,1);
%% run matlab's "intlinprog" command
numVariables = size(Aeq,2);
intcon = 1:numVariables;
lb = zeros(1,numVariables);
ub = ones(1,numVariables);
[x,fval,exitflag,output]=intlinprog(zeros(n^3,1),intcon,[],[],Aeq,beq,lb,ub);

LP: Optimal objective value is 0.000000.

Optimal solution found.

Intlinprog stopped at the root node because the objective value is within a gap tolerance of the optimal value,
options.AbsoluteGapTolerance = 0 (the default value). The intcon variables are integer within tolerance,
options.IntegerTolerance = 1e-05 (the default value).

exitflag;
output;
%% turn matlab's outputed solution vector x into sudoku terms
S=zeros(n,n);
for k=1:n
  subx=find(x((k-1)*n^2+1:k*n^2));
  for j=1:n
      row=mod(subx(j),n);
      if row==0
          row=n;
      end
      S(row,j)=k;
  end
end
% Sudoku Matrix S
S
S = 9×9
4 9 7 2 3 5 6 8 1
8 5 3 4 6 1 7 2 9
1 6 2 9 7 8 3 4 5
2 1 8 7 4 3 5 9 6
9 7 5 8 1 6 2 3 4
6 3 4 5 9 2 1 7 8
7 8 1 6 2 9 4 5 3
3 4 9 1 5 7 8 6 2
5 2 6 3 8 4 9 1 7

 

]]>
An Algorithmic Spelling Bee https://blogs.mathworks.com/community/2023/04/06/an-algorithmic-spelling-bee/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/04/06/an-algorithmic-spelling-bee/#comments Thu, 06 Apr 2023 18:15:54 +0000 https://blogs.mathworks.com/community/?p=9129

Earlier this year I wrote about solving word ladders with MATLAB. There was a lot of interest in that post, so I thought I'd share my investigations regarding another word-based app. In this script,... read more >>

]]>
Earlier this year I wrote about solving word ladders with MATLAB. There was a lot of interest in that post, so I thought I'd share my investigations regarding another word-based app. In this script, I'm trying to create a puzzle modeled on the NY Times Spelling Bee game. Here is the premise: you are given seven letters, and your job is to find all possible words you can make with those seven letters. You can use letters more than once, but they must be four or more letters long, and they must all include the special center letter. Every Spelling Bee puzzle has at least one "pangram", which is a word that uses all seven letters.
As an example, suppose you were given this puzzle.
spellingbee.png
From this puzzle you could create PORE, ADORE, ADOPT, as well as the pangram OPERATED. But you couldn't create POD (too short) or PAPER (doesn't include the center letter "O").
Here I'm not so much interested in solving the puzzle. I want to write a script that can create a Spelling Bee puzzle.

Build the Dictionary

We need some ground truth for all the legal words. Here's Google's 10,000 word English dictionary. It's small, but good enough for our purposes here.
url = 'https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt';
wordList = webread(url);
Split the word list into strings.
words = split(string(wordList));
words = lower(words);
The Spelling Bee puzzle avoids the letter S so that it never has to deal with plurals. Let's use logical indexing to keep only the words that don't contain an S.
keep = ~words.contains("s");
words = words(keep);
Of these, keep only the words that are four letters or longer.
keep = words.strlength >= 4;
words = words(keep);
I like how these string commands are easy to read and understand! Just like for us humans, code that communicates clearly keeps its job the longest. We don't want to employ fussy, high-maintenance code.
How many words do we end up with?
fprintf("The adjusted dictionary now contains %d words\n",length(words))
The adjusted dictionary now contains 4955 words
We've thrown out about half the words in our dictionary.
We'll be converting from ASCII representation to alphabet number a few times, so let's invest in a little anonymous helper function. It'll make the code below a little easier to read.
% An anonymous function to translate ASCII values to A=1, B=2, ... Z=26.
ascii2letter = @(chars) abs(lower(chars))-96;
Try it out
ascii2letter('ABCXYZ')
ans = 1×6
1 2 3 24 25 26
Looks good!
Build a 26-column sparse matrix to represent unique letter usage for each word. Each word in the dictionary gets one row. Every letter that appears in the word gets a 1.
dictionaryLength = numel(words);
a = sparse(dictionaryLength,26);
for i = 1:dictionaryLength
uniqueLetters = unique(words(i).char);
a(i,ascii2letter(uniqueLetters)) = 1;
end
nnz(a)/numel(a)
ans = 0.2218
At 22% full, this matrix isn't terribly sparse as sparse matrices go. But it's a fun excuse to play with SPARSE, so let's carry on. Here's a SPY plot of the matrix.
spy(a)
set(gca, ...
XTick=1:26, ...
XTickLabel=num2cell('A':'Z'), ...
XTickLabelRotation=0, ...
XAxisLocation="top", ...
PlotBoxAspectRatio=[1 1 1])
To make much out of this, we need to zoom in. Let's see how the word LABEL is encoded.
ix = 1002;
% In case you're wondering, I like to use "ix" as short for "index"
words(ix)
ans = "label"
full(a(ix,:))
ans = 1×26
1 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
spy(a(1001:1010,:))
xline([1 2 5 12])
yline(2,Color="red")
set(gca, ...
XTick=1:26, ...
XTickLabel=num2cell('A':'Z'), ...
XTickLabelRotation=0, ...
XAxisLocation="top", ...
YTick=1:10, ...
YTickLabels=words(1001:1010))
Note that even though the L appears twice in the word, it only has a one in the matrix.
Just for fun, let's do a histogram of the letters. This can be a useful sanity check that we're on the right track.
allLetters = ascii2letter(char(join(words,'')));
histogram(allLetters)
set(gca, ...
XTick=1:26, ...
XTickLabel=num2cell('A':'Z'), ...
XTickLabelRotation=0)
As expected, E is the most commonly appearing letter. Q is the least, but for the fact that we completely wiped out S.
How many words are composed of exactly seven distinct letters? That is, how many are potential pangrams for a game?
% Summing letter-use across the rows
% Use FIND to build an index to all the words that use exactly seven letters
ix7LetterWords = find(sum(a,2)==7);
length(ix7LetterWords)
ans = 790
Let's look at a few of these seven-letter words.
num7LetterWords = numel(ix7LetterWords);
ix = ix7LetterWords(1:10);
disp(words(ix(1:10)))
"product"
"privacy"
"company"
"project"
"american"
"network"
"following"
"including"
"location"
"profile"
Pick a good one as the "seed" pangram for our game.
ix = ix(9);
disp(words(ix))
location
How many words can be spelled from those same 7 letters? Find all the words that use nothing but the letters in the seed word
lettersInSeedWord = a(ix,:);
% Find all the words that have none of the letters from the seed word.
% We're making sure that all contributions of letters other than
% the seed letters sum to zero.
ixWordsFromSeedWord = find(sum(a(:,~lettersInSeedWord),2) == 0);
fprintf('%d words use only the seven letters appearing in the seed word.\n',numel(ixWordsFromSeedWord))
73 words use only the seven letters appearing in the seed word.
Which letters appear most frequently?
bar(sum(a(ixWordsFromSeedWord,:)))
set(gca, ...
XTick=1:26, ...
XTickLabel=num2cell('A':'Z'), ...
XTickLabelRotation=0)
We need to designate one letter as the "center letter" that must appear in every word. Let's pick the letter that appears least frequently.
vals = full(sum(a(ixWordsFromSeedWord,:)));
vals(vals==0) = inf;
[~,ixlet] = min(vals);
centerLetter = char(ixlet+96);
Remove all the words that don't have this letter
ixRequired = find(a(:,ixlet));
ix2a = intersect(ixWordsFromSeedWord,ixRequired);
This is the original seed word:
fprintf("%s\n", words(ix))
location
Here are the seven unique letters:
sevenLetters = unique(char(words(ix)));
fprintf("%s\n", sevenLetters);
acilnot
The required center letter is:
fprintf("%s\n", upper(centerLetter));
C
Here are the pangrams
ix3 = find(sum(a(ix2a,:),2)==7);
for i = 1:numel(ix3)
fprintf("%s\n",words(ix2a(ix3(i))));
end
location
coalition
allocation
Here is the complete list of words
for i = 1:numel(ix2a)
fprintf("%s\n",words(ix2a(i)));
end
contact
local
location
call
action
cool
clinical
canon
icon
contain
atlantic
cotton
lincoln
clinton
cincinnati
clinic
coalition
coat
allocation
ncaa
coal
oclc
coin
citation
colin
ciao
cant
canal
colonial
clan
italic
incl
colon
cannon
Some of those are little odd, but we have our dictionary to thank for that.
sixLetters = setdiff(sevenLetters,centerLetter);
sixLetters = sixLetters(randperm(6));
Now for the graphics! Make the plot
% The perimeter hex cells are centered from pi/6 to 11*pi/6 radians
t = 2*pi*(0:5)/6 + 2*pi/12;
r = 1.08*sqrt(3);
x = r*cos(t);
y = r*sin(t);
cla
hexplot(0,0,upper(centerLetter),"#F7DA21")
hold on
for i = 1:numel(x)
hexplot(x(i),y(i),upper(sixLetters(i)),"#E6E6E6")
end
hold off
axis equal
axis off
And there you have it! It's easy to see how valuable a good algorithmically generated game can be. Once you've worked out the logic, you just need to run it once every day and your puzzle is ready to go. Compare this with the labor that goes into a crossword puzzle. Although who knows? Maybe crossword puzzles will be yet another of those things that AI proves to be adept at.
function hexplot(x,y,letter,color)
t = linspace(0,2*pi,7);
patch(cos(t)+x,sin(t)+y,"white", ...
EdgeColor="none", ...
FaceColor=color)
text(x,y,letter, ...
FontSize=24, ...
FontWeight="bold", ...
HorizontalAlignment="center", ...
VerticalAlignment="middle")
end

]]>
https://blogs.mathworks.com/community/2023/04/06/an-algorithmic-spelling-bee/feed/ 9
Celebrate pi day with a pi patch https://blogs.mathworks.com/community/2023/03/14/celebrate-pi-day-with-a-pi-patch/?s_tid=feedtopost https://blogs.mathworks.com/community/2023/03/14/celebrate-pi-day-with-a-pi-patch/#comments Tue, 14 Mar 2023 11:09:28 +0000 https://blogs.mathworks.com/community/?p=9087 Pi patch

Today's guest article is by Adam Danz whose name you might recognize from the MATLAB Central community. Adam is a developer on the MATLAB Graphics and Charting team. About 20 years ago Adam... read more >>

]]>
Today's guest article is by Adam Danz whose name you might recognize from the MATLAB Central community. Adam is a developer on the MATLAB Graphics and Charting team. About 20 years ago Adam memorized pi to a measly 200 decimal places which is 1/50 of the digits he'll visualize today using MATLAB.

It's March 14th. Let's get irrational.

Today is pi day, the most popular irrational number at any party, transcendental to all number systems, with an infinite number of decimal places.

But how many decimal places are needed? NASA's Jet Propulsion Laboratory uses 15 decimal places of pi for interplanetary navigation. With 15 decimals of pi, the earth's circumference can be calculated from its 12756 km (7926 mi) diameter with an error the size of a molecule. The figure below shows the increase in precision (decrease in error) of calculating the earth's circumference as more digits of pi are included in the calculation c=πd.

.

The value of pi in MATLAB, like most other technical computing environments, loses precision after the 15th decimal place due to limitations of floating point arithmetic. To get more than 15 decimal places of pi we can set variable precision that converts symbolic expressions to floating-point numbers, provided by the Symbolic Math Toolbox.
Since we're being irrational, let's get 10,000 decimal places of pi.
% Requires the Symbolic Math toolbox
symExpression = sym(pi); % Symbolic expression; e.g. sym(pi), exp(sym(1)), sym(1/23)
nDecimalPlaces = 10000; % Number of decimal places
decimalChar = char(vpa(mod(abs(symExpression),1),nDecimalPlaces+3))
decimalChar = '0.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632788659361533818279682303019520353018529689957736225994138912497217752834791315155748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035637076601047101819429555961989467678374494482553797747268471040475346462080466842590694912933136770289891521047521620569660240580381501935112533824300355876402474964732639141992726042699227967823547816360093417216412199245863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818347977535663698074265425278625518184175746728909777727938000816470600161452491921732172147723501414419735685481613611573525521334757418494684385233239073941433345477624168625189835694855620992192221842725502542568876717904946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886269456042419652850222106611863067442786220391949450471237137869609563643719172874677646575739624138908658326459958133904780275900994657640789512694683983525957098258226205224894077267194782684826014769909026401363944374553050682034962524517493996514314298091906592509372216964615157098583874105978859597729754989301617539284681382686838689427741559918559252459539594310499725246808459872736446958486538367362226260991246080512438843904512441365497627807977156914359977001296160894416948685558484063534220722258284886481584560285060168427394522674676788952521385225499546667278239864565961163548862305774564980355936345681743241125150760694794510965960940252288797108931456691368672287489405601015033086179286809208747609178249385890097149096759852613655497818931297848216829989487226588048575640142704775551323796414515237462343645428584447952658678210511413547357395231134271661021359695362314429524849371871101457654035902799344037420073105785390621983874478084784896833214457138687519435064302184531910484810053706146806749192781911979399520614196634287544406437451237181921799983910159195618146751426912397489409071864942319615679452080951465502252316038819301420937621378559566389377870830390697920773467221825625996615014215030680384477345492026054146659252014974428507325186660021324340881907104863317346496514539057962685610055081066587969981635747363840525714591028970641401109712062804390397595156771577004203378699360072305587631763594218731251471205329281918261861258673215791984148488291644706095752706957220917567116722910981690915280173506712748583222871835209353965725121083579151369882091444210067510334671103141267111369908658516398315019701651511685171437657618351556508849099898599823873455283316355076479185358932261854896321329330898570642046752590709154814165498594616371802709819943099244889575712828905923233260972997120844335732654893823911932597463667305836041428138830320382490375898524374417029132765618093773444030707469211201913020330380197621101100449293215160842444859637669838952286847831235526582131449576857262433441893039686426243410773226978028073189154411010446823252716201052652272111660396665573092547110557853763466820653109896526918620564769312570586356620185581007293606598764861179104533488503461136576867532494416680396265797877185560845529654126654085306143444318586769751456614068007002378776591344017127494704205622305389945613140711270004078547332699390814546646458807972708266830634328587856983052358089330657574067954571637752542021149557615814002501262285941302164715509792592309907965473761255176567513575178296664547791745011299614890304639947132962107340437518957359614589019389713111790429782856475032031986915140287080859904801094121472213179476477726224142548545403321571853061422881375850430633217518297986622371721591607716692547487389866549494501146540628433663937900397692656721463853067360965712091807638327166416274888800786925602902284721040317211860820419000422966171196377921337575114959501566049631862947265473642523081770367515906735023507283540567040386743513622224771589150495309844489333096340878076932599397805419341447377441842631298608099888687413260472156951623965864573021631598193195167353812974167729478672422924654366800980676928238280689964004824354037014163149658979409243237896907069779422362508221688957383798623001593776471651228935786015881617557829735233446042815126272037343146531977774160319906655418763979293344195215413418994854447345673831624993419131814809277771038638773431772075456545322077709212019051660962804909263601975988281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267945612753181340783303362542327839449753824372058353114771199260638133467768796959703098339130771098704085913374641442822772634659470474587847787201927715280731767907707157213444730605700733492436931138350493163128404251219256517980694113528013147013047816437885185290928545201165839341965621349143415956258658655705526904965209858033850722426482939728584783163057777560688876446248246857926039535277348030480290058760758251047470916439613626760449256274204208320856611906254543372131535958450687724602901618766795240616342522577195429162991930645537799140373404328752628889639958794757291746426357455254079091451357111369410911939325191076020825202618798531887705842972591677813149699009019211697173727847684726860849003377024242916513005005168323364350389517029893922334517220138128069650117844087451960121228599371623130171144484640903890644954440061986907548516026327505298349187407866808818338510228334508504860825039302133219715518430635455007668282949304137765527939751754613953984683393638304746119966538581538420568533862186725233402830871123282789212507712629463229563989898935821167456270102183564622013496715188190973038119800497340723961036854066431939509790190699639552453005450580685501956730229219139339185680344903982059551002263535361920419947455385938102343955449597783779023742161727111723643435439478221818528624085140066604433258885698670543154706965747458550332323342107301545940516553790686627333799585115625784322988273723198987571415957811196358330059408730681216028764962867446047746491599505497374256269010490377819868359381465741268049256487985561453723478673303904688383436346553794986419270563872931748723320837601123029911367938627089438799362016295154133714248928307220126901475466847653576164773794675200490757155527819653621323926406160136358155907422020203187277605277219005561484255518792530343513984425322341576233610642506390497500865627109535919465897514131034822769306247435363256916078154781811528436679570611086153315044521274739245449454236828860613408414863776700961207151249140430272538607648236341433462351897576645216413767969031495019108575984423919862916421939949072362346468441173940326591840443780513338945257423995082965912285085558215725031071257012668302402929525220118726767562204154205161841634847565169998116141010029960783869092916030288400269104140792886215078424516709087000699282120660418371806535567252532567532861291042487761825829765157959847035622262934860034158722980534989650226291748788202734209222245339856264766914905562842503912757710284027998066365825488926488025456610172967026640765590429099456815065265305371829412703369313785178609040708667114965583434347693385781711386455873678123014587687126603489139095620099393610310291616152881384379099042317473363948045759314931405297634757481193567091101377517210080315590248530906692037671922033229094334676851422144773793937517034436619910403375111735471918550464490263655128162288244625759163330391072253837421821408835086573917715096828874782656995995744906617583441375223970968340800535598491754173818839994469748676265516582765848358845314277568790029095170283529716344562129640435231176006651012412006597558512761785838292041974844236080071930457618932349229279650198751872127267507981255470958904556357921221033346697499235630254947802490114195212382815309114079073860251522742995818072471625916685451333123948049470791191532673430282441860414263639548000448002670496248201792896476697583183271314251702969234889627668440323260927524960357996469256504936818360900323809293459588970695365349406034021665443755890045632882250545255640564482465151875471196218443965825337543885690941130315095261793780029741207665147939425902989695946995565761218656196733786236256125216320862869222103274889218654364802296780705765615144632046927906821207388377814233562823608963208068222468012248261177185896381409183903673672220888321513755600372798394004152970028783076670944474560134556417254370906979396122571429894671543578468788614445812314593571984922528471605049221242470141214780573455105008019086996033027634787081081754501193071412233908663938339529425786905076431006383519834389341596131854347546495569781038293097164651438407007073604112373599843452251610507027056235266012764848308407611830130527932054274628654036036745328651057065874882256981579367897669742205750596834408697350201410206723585020072452256326513410559240190274216248439140359989535394590944070469120914093870012645600162374288021092764579310657922955249887275846101264836999892256959688159205600101655256375679'
To use each decimal digit independently, convert the character array to a numeric vector.
decvec = decimalChar(3:end-3) - '0'
decvec = 1×10000
1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4 1 9 7 1 6 9 3 9 9 3 7 5 1 0

Create a pi patch

10,000 decimals of pi are efficiently visualized as a single Patch object. Each digit is assigned an angular coordinate evenly distributed within 10 wedges, one wedge for each value 0 to 9. Lines segments connect adjacent digits starting with 1-to-4, 4-to-1, 1-to-5, 5-to-9, 9-to-2 and so on, moving slightly counterclockwise within each wedge. Each line segment is colored according to its length.
% Assign each digit an angular coordinate based on its value 0:9
nDecimals = numel(decvec);
theta = ((0:36:324)+(0:36/nDecimals:36)')*pi/180;
ang = theta(sub2ind(size(theta),1:nDecimals,decvec+1));
% Compute the length of each line segment; used to set color
[x,y] = pol2cart(ang,1);
[~,~,d] = uniquetol(hypot(diff(x),diff(y)));
alpha = min(0.85,max(0.006, 1000/nDecimals));
% Plot line segments using the edge property of a single Patch object
fig = figure(Color='k');
fig.Position(3:4) = 600;
movegui(fig)
ax = axes(fig);
p = patch(ax,XData=x,YData=y,FaceColor='none',EdgeAlpha=alpha);
set(p,'FaceVertexCData', [d;nan], 'EdgeColor','Flat')
colormap(ax,jet(10))
axis equal off
% Add pi character
text(0,0.05,'\pi', ...
HorizontalAlignment='Center', ...
FontUnits='normalized', ...
FontSize = 0.2, ...
Color = 'k');
% wedge lines
th = linspace(0,2*pi,1000);
gaps = 0 : pi/5 : 2*pi;
isgap = any(abs(th-gaps') < pi/120);
th(isgap) = nan;
radius = 1.08;
[segx,segy] = pol2cart(th,radius);
hold on
plot(segx,segy,'-',LineWidth=1,Color=[.8 .8 .8])
% wedge labels
midAng = gaps(1:end-1) + pi/10;
tradius = radius + .08;
[tx,ty] = pol2cart(midAng,tradius);
text(tx, ty, string(0:9), ...,
FontUnits='normalized',...
FontSize=0.05, ...
Color=[.8 .8 .8], ...
HorizontalAlignment='center',...
VerticalAlignment='middle');
To animate the visualization, each line segment was plotted individually and a frame was captured every 200 iterations using getframe, written to a gif file using imwrite with a delay of 0.2 sec.
AnimatedPolarPi_50dFrames.gif

Visualizing patterns in decimals

We can use this visualization to investigate patterns in several approximations of pi by replacing the symExpression variable with sym(22/7), sym(333/106), sym(355/113), and sym(103993)/sym(33102).
piApproximations.png

More fun

  • Use the vector of pi digits, decvec, to create a different visual representation of pi.
  • Visualize different symbolic expressions by replacing the value in symExpression.
  • What would digits of e look like? exp(sym(1))
  • How about √2 ? sqrt(sym(2))
  • Check out sym(1/9973), sym(1/23), sym(1/42), sym(1/49), sym(1/31), sym(1/61), sym(2/11)
I'd love to see your creations in the comments below!
]]>
https://blogs.mathworks.com/community/2023/03/14/celebrate-pi-day-with-a-pi-patch/feed/ 1