You’re part of a long tradition. Communities don’t blossom in one night. MATLAB’s rich community has been growing steadily for many years, and today I want to give you an idea of just how long. I bet it’s longer than you think! I’m talking about history here because we want to celebrate the fact... read more >>

]]>Communities don’t blossom in one night. MATLAB’s rich community has been growing steadily for many years, and today I want to give you an idea of just how long. I bet it’s longer than you think!

I’m talking about history here because we want to celebrate the fact that MATLAB Central is 15 years old. That’s pretty old in web years. In 2001 there was no iPhone, no YouTube, no Facebook. Wikipedia launched that same year. But old as it is, MATLAB Central was just giving a modern web-based home to a community that was already thriving.

Let’s rewind the clock even further. The original FORTRAN version of MATLAB goes back to a class Cleve Moler taught at Stanford in 1979. MathWorks incorporated as a company in 1984, by which time the commercial version of MATLAB had been re-written in C. So the company was already nine years old when, in 1993, we launched three “electronic services for MATLAB/Simulink users.” These were the anonymous FTP site where people could share files, the comp.soft-sys.matlab newsgroup where people could chat and ask questions, and the MathWorks Digest email newsletter.

And because the web never forgets anything, we can still find Volume 1, Number 1 of the MathWorks Digest. First published in August 1993, it features an introduction by Cleve Moler. I notice some of the pixels are yellowing with age, but other than that, it’s holding up pretty well.

Think about it: in 1993, email was still kind of a big deal. Nobody knew about the web back then because… there was no web. Or rather, it was in such an embryonic stage that only Sir Tim and Marc Andreesen knew about it (the first popular web-browser, NCSA Mosaic, launched in April 1993). As the web grew, the folks at NCSA maintained a “What’s New” list for cool new websites. That is, the web was so small that one site could claim to tell you about *everything new*. MathWorks had one of the first corporate websites, and we were able to make the NCSA list in February of 1994. I remember this because I was the guy who sent them the link.

And because the web never forgets anything, you can still see it: What’s New! February 1994. Look for us under February 5th.

It’s no surprise that most of the links on this ancient page don’t work anymore. But the MathWorks links still work. Click on the MATLAB gallery link and it takes you to… (wait for it) the File Exchange! Those roots go back as far as the web goes.

I’m sharing this ancient history mostly to emphasize that the community site we launched in 2001 was actually built on the foundations of a robust community that was already two decades old. We took all the files from the old FTP site and moved them over to a web-based service we called the File Exchange. And we built a web front-end for the MATLAB newsgroup and called it the Newsreader. These two applications, the File Exchange and the Newsreader (along with a programming contest), were together called MATLAB Central. The web version of our MATLAB community was born.

*[Thanks to former MathWorker Drea Thomas for helping me recall some of this ancient history.]*

MATLAB Central launched 15 years ago, in the fall of 2001, and it’s been growing fast ever since. I’ve had a front row seat for the entire show, and it’s been great fun. I’m writing this partly to share some of that history with you, and partly to say thanks.... read more >>

]]>This is not just any Viking ship. Back in September of 2001, this was one of the first submissions to the the newly launched File Exchange. It’s been there ever since. Check it out! (I just ran the code in MATLAB 2016a, and can verify that it still works.) We on the original MATLAB Central team loved this image. We put it on the wall so it would remind us how awesome MATLAB users are and why we should work hard to build the community they deserve.

Who made the ship? Pontus Axelsson made it. When I was contemplating the history of MATLAB Central, I remembered this ship and what it meant to us. I began to wonder if I could track down Pontus, thank him, and maybe learn more about the ship. I am very happy to report that today he is alive and well and running a company that makes apps for smartphones and tablets.

This is Pontus (2016 edition).

He doesn’t use MATLAB much anymore, but he was happy to recall the story of the Viking ship. In 1995 he was working on a Master’s degree in Computer Science at the Royal Institute of Technology in Stockholm. That’s when he first came across MATLAB. His words tell the story best.

I was given an assignment to render a simple rowboat in 3D using cubic Bézier curves and calculate water displacement. I was immediately intrigued by the power of Matlab. I had previous experience using tools like Adobe Illustrator, so I had some knowledge of vector graphics. But with Matlab I could do so much more. It could tell me stuff, rather than just visualize; I could simulate reality, and control everything. A simple assignment turned into something much bigger as I set out to “push the envelope”.

The ship was “drawn by eye”, but inspired by Explorer Vodka, probably the cheapest vodka you could buy at the time. Great for students. The pink delta on the shields is the logo of the Computer Science student section. When the ship was complete, I proceeded to add multiple color ranges to the rendering – which wasn’t really straightforward in Matlab at the time – and to animate it. It was such a joy to explore the possibilities.

This Viking ship signifies for me all that is great about the MATLAB community. Over the years, many powerful and useful algorithms have been contributed to the File Exchange, but this magnificent ship grew beyond the bounds of a school project not just because it was functional or accurate but because it was wonderful. It exists because of the joy of expression and the joy of sharing. MATLAB is canvas and paint and Pontus made something beautiful. So I thank him and I thank all of you who have contributed your own wonderful files over the years. Here is a toast to 15 more years. Will you send us *your* Viking ship?

In my next post, I will say more about the history of MATLAB Central, but today I will close with an image of the site circa October 2001. Note the antique version of Internet Explorer.

Look carefully and you’ll see that we liked the Viking ship so much that we put it into our free MATLAB screensaver. And I can’t resist showing you just a little more Nordic grandeur. Pontus, it turns out, wasn’t satisfied with just a static image of a Viking ship. He used MATLAB to generate an animation of it sailing across the Baltic, which he then rendered into an MPEG file. I must remind you this was not a simple task back in the Elder Days of the last century. I’ve taken his animation and re-rendered it as an animated GIF. Please enjoy.

Look at those oars! Look at that fluttering banner streaming o’er the billowing sea! I think I need some Explorer Vodka.

ALSO: I should mention that we are celebrating our birthday with some online games. See MATLAB Central Anniversary.

]]>We did some web updates last night, and Cody emerged with a fresh coat of paint. As a result it’s more mobile-friendly. The tags for each problem are a little more prominent on the right side. But I especially want to call your attention to the fact that code regions now feature... read more >>

]]>I want to show you what it looks like with a problem that John D’Errico created a few weeks ago. The problem, Counting the Grand Primes, asks you to look for prime pairs that differ by exactly 1000. The leading answer is by Peng Liu.

**Spoiler Alert!** If you haven’t solved this problem yet, you wouldn’t ordinarily be allowed to look at this solution. But I’m going to show you anyway, because it’s a nice solution and a good illustration of the new feature.

Ooh! Line numbers! Notice that the keywords “function” and “end” are blue and the comments are green. Thoughtfully, Peng has provided not just one, but three solutions. Two of them excel in the Cody sense: they don’t use a lot of code. But we all know there’s more to life than being short. The first one runs faster because you compute the prime numbers once rather than twice. Since two of the solutions are commented out, they appear in green.

If you do a lot of MATLAB programming, you’ll appreciate how important syntax highlighting is to your coding practice. It should make it easier to create and interpret solutions.

]]>Let’s say you’ve written some code that you think might worth adding to the File Exchange. But then you hesitate. Your Tiddlywinks Trajectory Simulator function (TiddleSim.m) is nifty. It’ll definitely be the first of its kind on the site. But you ask yourself: Should I really put this on the... read more >>

]]>My friend, I’m here to encourage you to submit that file.

Not everybody will find it interesting, but I guarantee you someone will. And I know the secret to dramatically increasing the number of people who find it interesting. Here it is.

The very best way to get people to use and enjoy your code is to include some help and examples in your function comments.

Is there a standard way to do that? Yes there is. Take a look at this documentation page. It spells out how we structure function help here at MathWorks. You don’t have to use this format, but it’s served us very well, and if you do you’ll be using a standard that people around the world are familiar with. So I’m going to strongly recommend that you use it unless you have compelling reasons not to.

The anatomy of function help, at its simplest, is this. Just below the function signature you put the H1 line. This is followed by the calling syntax. At the end you might want to link to other functions in a See Also line.

Here is a sophisticated function called ADDME. We’ll use it as our help model.

The H1 line is very cleverly named. It is the first line you see when you type help on the function (that is, “help addme”). The H1 lines starts with the name of the function followed by a short sentence (it has to fit on one line!) describing the function.

If you’ve made it this far and you really want to rock the world with your function, add some examples to your help. That way people can see not only the abstract calling syntax, but also how it looks in action.

I dipped into the File Exchange and found a popular function with terrific help: Fast ‘n easy smoothing written by Damien Garcia. Download it and look at the help. It starts off like this.

>> help smoothnsmoothnRobust spline smoothing for 1-D to N-D data.smoothnprovides a fast, automatized and robust discretized spline smoothing for data of arbitrary dimension.

But it goes on and on from there, with lots of detail and references, and no fewer than eight (!) examples. Beautiful! That, my friends, is how you make your code helpful.

Since Damien works in a lab that does heart imaging, it’s only appropriate that I should include this example from his file: smoothing a cardioid.

t = linspace(0,2*pi,1000); x = 2*cos(t).*(1-cos(t)) + randn(size(t))*0.1; y = 2*sin(t).*(1-cos(t)) + randn(size(t))*0.1; z = smoothn({x,y}); plot(x,y,'r.',z{1},z{2},'k','linewidth',2) axis equal tight

Be like Damien. Have a heart. Think of your File Exchange friends. A little help can make all the difference.

]]>*It’s fun to follow along behind an expert, because even with a seemingly simple problem like summing consecutive integers, there’s always more going on than you first realize. And there’s always a new approach to the problem that you would have never considered.*

*Thanks John!*

*-Ned.*

*by John D’Errico*

As an occasional Project Euler solver who has solved several hundred problems (all but one of them in MATLAB, the odd one out I did by hand) Cody intrigues me. So I spent a little time with Cody yesterday. Here are my thoughts, that perhaps you might want to pass along.

Really, mainly I looked at one problem, a rather arbitrary one from the top of the stack. I picked problem 189 to look at. The question was to compute the sum of the integers from 1 to 2^n.

Clearly the simple solution, in fact, one might argue the classic MATLAB solution is simply

y = sum(1:2^n);

Of course this is fast to compute, easy to read, and very obvious what the code does. This is the solution I would jump to almost always, EXCEPT when n is large. For example, what happens if n is 25? 100? The classic solution above will fail to return a result for n=100 before the universe dies from heat death, as 2^100 is such a huge number that any modern computer will never terminate the computation. And simply trying to generate a vector of length 2^100 will exceed the RAM in any computer we could ever imagine. So the classic solution fails miserably, for SOME n. On my machine, I get the following times:

>> timeit(@() sum(1:2^5)) ans = 1.2278e-06 >> timeit(@() sum(1:2^10)) ans = 4.911e-06 >> timeit(@() sum(1:2^15)) ans = 7.7062e-05 >> timeit(@() sum(1:2^20)) ans = 0.002765 >> timeit(@() sum(1:2^25)) ans = 0.1736

As you can see, when n starts to be large enough that the vectors are significantly large, the time also becomes significant, and does so quickly. I would not bother to try it for n=30. The point is that the classic solution fails because it uses an algorithm that is O(2^n). Of course algorithms that suffer from such exponential growth are problematic. This one is fine as long as n is never larger than around 15-20. But exponential run time hits a computational brick wall very quickly.

The solution might be to choose to look more closely at the problem. Is there a mathematical way to reduce the time needed? Clearly, the necessary sum is easy to compute IF one recognizes that for any positive integer n, one can write the integers in the set [1:2^n] as:

[1:2^(n-1) , 2^(n-1) + 1:2^(n-1)]

This merely reflects the binary expansion of these numbers. However it also gives us a nice way to write the desired sum in a recursive fashion. That is, we can write the solution as:

sum_int(n) = sum_int(n-1) + (2^(n-1))^2

So a better code, at least for purely non-negative integer n, might be something like this:

function y = sum_int(x) % For non-negative integer input x, compute the sum of the integers 1:2^x if x == 0 % special case to end the recursion y = 1; else y = 2*sum_int(x - 1) + 2^(2*x-2); end

So we see that sum_int as written above, is actually faster to run, even for n as small as 5, and that the time seems to be linear in n. As one should recognize, sum_int is indeed an O(n) algorithm as written above.

>> timeit(@() sum_int(5)) ans = 7.5692e-07 >> timeit(@() sum_int(10)) ans = 1.7227e-06 >> timeit(@() sum_int(15)) ans = 2.6715e-06 >> timeit(@() sum_int(20)) ans = 3.7462e-06 >> timeit(@() sum_int(25)) ans = 4.6515e-06 >> timeit(@() sum_int(100)) ans = 1.772e-05

In fact, one can even use sum_int to compute the exact value for sym input. Of course sym slows it down, but even that takes only 1/2 second to compute.

>> timeit(@() sum_int(sym(100))) ans = 0.54818 >> sum_int(sym(100)) ans = 803469022129495137770981046171215126561215611592144769253376 >> sum_int(sym(1000)) ans = 57406534763712726211641660058884099201115885104434760023882136841288313069618515692832974315825313495922298231949373138672355948043152766571296567808332659269564994572656140000344389574120022435714463495031743122390807731823194181973658513020233176985452498279081199404472314802811655824768082110985171698215120385828833994926435042413009836474525915918251720110295164670516628746730606637774712420949241272862285974797636825655630482650144583914557794004353013244164891007287546556882572164179254268468766736029354798734808092593495610026430676423398598185956607671495251600324809039074511028408549376

An interesting question is if n should be an integer. Should the code produce an error when n is not integer? Or should it merely produce a result for any non-negative floating point number? My point is that error checking is an important part of good code, as is good documentation that indicates the behavior of the code under all circumstances. So sum_int as written will fail when n is 2.5, or pi, or any non-integer.

Next, a serious problem with SOME recursive schemes is they can suffer from exponential growth themselves. E.g., using recursion to compute the n’th Fibonacci number is a classically poor way to solve the problem. A simple loop (thus O(n)) suffices for reasonably small Fibonacci numbers, although for huge n, there are better schemes to compute Fibonacci numbers that are only O(log2(n)) in complexity. Regardless, one can re-write the function sum_int with a for loop even though the recursive nature of the code is not truly an issue for this problem.

function y = sum_int2(x) % For non-negative integer input x, compute the sum of the integers 1:2^x y = 1; for k = 1:x y = 2*y + 2^(2*k-2); end

This simpler, non-recursive code is as easy to read as the recursive code, and it will run more quickly yet, since it does not suffer from recursive function call overhead. However, it will not produce correct results for sym input. One could fix that problem too, with some effort.

Okay, is this the end of such a discussion? Of course not. We can return to the famous solution by Gauss, that recognizes the natural symmetry in the problem. Thus if we write the sum of the integers

0,1,2, … 2^n-2, 2^n-1, 2^n

then we can compress the sum down by adding them in a different order.

(0 + 2^n) + (1 + 2^n-1) + (2 + 2^n-2) + …

So, the famous formula (attributed to Gauss) for the sum of the integers from 0 to k, can be written as

k*(k+1)/2

Therefore we can write a simpler version yet of this code:

sum_int3 = @(n) 2^n*(2^n+1)/2;

This works because the sum of the integers 0:k is the same as the sum of the integers 1:k. Of course, it produces the correct result, and it is quite fast. As well, it works for any class of input that supports the necessary arithmetic operations.

>> sum_int3(sym(100)) ans = 803469022129495137770981046171215126561215611592144769253376 >> timeit(@() sum_int3(sym(100))) ans = 0.0031585

So any in-depth discussion of the problem should explain issues like this. I’d argue that virtually every problem in Cody would/could benefit from a discussion like this, where the reader can learn how to recognize when a simple algorithm that does quite well for some inputs, may still fail miserably for other input.

Should Cody have some mechanism for expert solvers to explain issues like this? I guess that is up to you to decide, but I would argue that an earnest student could learn a great deal from such a discussion.

In summation, I realize the lessons in my comments are fairly classic:

When writing code, your goal at first should be to find a solution that is at least viable. Get it working FIRST. If there is a problem with time or memory, etc., only then do you consider optimizing your code. Programmers (me included) can often spend far too much time optimizing code that has no need for that.

Programmer time is generally far more valuable than cpu time. So avoid pre-optimization of your code.

When you do look for a code optimization, there are many ways to solve any problem. Sometimes a vectorized solution will be right. Sometimes a looped solution is better. And sometimes it is right to look for mathematical insight to find a completely different solution.

John

]]>Let me start with a graphical riddle. In what sense is the following equivalence true? To learn the answer, read on! I recently came across Nick Higham’s fun post on one-liners in MATLAB. That piece and the approach of Bastille Day on July 14th made me think of another one-line program. image([3 2... read more >>

]]>To learn the answer, read on!

I recently came across Nick Higham’s fun post on one-liners in MATLAB. That piece and the approach of Bastille Day on July 14th made me think of another one-line program.

image([3 2 1]);colormap(flag)

Pretty impressive, considering that it’s only 29 characters long. Is this the shortest flag program we can write?

As I thought about flags and MATLAB, I gave myself the following task. Using only the colormap “flag” and images of vectors, how many national flags can we construct? Probably more than you might guess. Let’s go on a little tour.

Proper flags shouldn’t have numbers running their edges, so I’d like to hide the tick marks and labels. Since I plan to do this multiple times in the script below, I’m going to use an anonymous function for compactness. It’s not necessary, but I like how it keeps the code tidy.

notick = @(ax) set(ax,'XTick',[],'YTick',[])

notick = @(ax)set(ax,'XTick',[],'YTick',[])

In honor of Bastille Day, we start with France.

france = [3 2 1]

france = 3 2 1

```
image(france)
title('Vive la France!')
notick(gca)
```

France is the only red, white, and blue tricolor with vertical bars. But if we look at horizontal patterns, we find many more.

Netherlands is a rotated version of France.

netherlands = rot90(france)

netherlands = 1 2 3

```
image(netherlands);
title('The Netherlands')
notick(gca)
```

Luxembourg, next door to the Netherlands, uses essentially the same flag. A pedantic Luxembourger or professional vexillologist may protest that the colors are slightly lighter and the aspect ratio is slightly different. We will gloss over these details.

luxembourg = netherlands

luxembourg = 1 2 3

```
image(luxembourg)
title('Luxembourg')
notick(gca)
```

thailand = [netherlands; flipud(netherlands)]

thailand = 1 2 3 3 2 1

```
image(thailand)
title('Thailand')
notick(gca)
```

Now we see the significance of the graphical riddle that we listed at the top of this post.

Russia’s flag is a variant on the three horizontal bands. We’ll use circshift to do a circular permutation of the colors in the Netherlands flag.

russia = circshift(netherlands,2)

russia = 2 3 1

```
image(russia)
title('Russia')
notick(gca)
```

austria = netherlands([1 2 1])

austria = 1 2 1

```
image(austria)
title('Austria')
notick(gca)
```

indonesia = netherlands(1:2)

indonesia = 1 2

```
image(indonesia)
title('Indonesia')
notick(gca)
```

monaco = indonesia

monaco = 1 2

```
image(monaco);
title('Monaco')
notick(gca)
```

poland = flipud(monaco)

poland = 2 1

```
image(poland);
title('Poland')
notick(gca)
```

There you have it. A veritable Tour d’Image. I count nine separate vector flags using only red, white, or blue. Did I miss any?

As an exercise for the reader, express all flags in terms of the vector “france”.

In the comments, Matt Tearle points out another flag that fits the model. It’s a kind of dual to Thailand. I am now convinced that vexillology conventions should always occur in the Netherlands, its flag being the indispensable element at the center of all flag alchemy.

costarica = [flipud(netherlands); netherlands]

costarica = 3 2 1 1 2 3

```
image(costarica);
title('Costa Rica')
notick(gca)
```

And Richard Alcock from MathWorks UK writes in to give us this timely and poignant example.

reflex_blue = [0 51 153]/255; yellow = [255 204 0]/255; [x, y] = pol2cart(linspace(0, 2*pi, 13), 1/3); plot(x, y, 'p', 'MarkerSize', 20, ... 'MarkerEdgeColor', yellow, 'MarkerFaceColor', yellow); axis('equal'); set(gca, 'Color', reflex_blue, ... 'XTick', [], 'YTick', [], ... 'Xlim', [-.75 .75], 'Ylim', [-.5, .5])

Sean de Wolski reminded me that black is one of the four colors of the “flag” colormap, thereby letting us add the Yemeni flag to our list. I thought the addition of black might give us a few more flags, but Yemen seems to be the end of it.

```
yemen = [1; 2; 4];
image(yemen)
title('Yemen')
notick(gca)
```

]]>Collaboration on software can be a lot of fun, but it can also be hard to motivate. For instance, you may be working on a project and you’d love some help, but you can’t get anyone else excited about your Interactive Polhode-Herpolhode Animator. Alternatively, you may be willing to help with... read more >>

]]>Collaboration on software can be a lot of fun, but it can also be hard to motivate.

For instance, you may be working on a project and you’d love some help, but you can’t get anyone else excited about your Interactive Polhode-Herpolhode Animator. Alternatively, you may be willing to help with somebody else’s project, but how do you find something that’s interesting to you and simultaneously needs and wants your help? Because if you’re going to spend time hacking code, you want to make sure somebody actually cares.

Well, this is your lucky day: I have solved that problem for you.

I have a project that is both intensely interesting and extraordinarily useful. It only needs a little help from you to realize its full potential.

The project is Export figure to 3D interactive PDF by Ioannis Filippidis (MATLAB Central, GitHub, CalTech). It lets you export a MATLAB figure to a U3D file. Or you can generate the same figure directly in a PDF file. Adobe Reader lets you drag it around like this. Try it yourself with this example file (PDF) or just look at the animation below. Pretty neat, eh?

If you look at the comments, you’ll see a lot of people really like it. But you can also see that it suffers from a few compatibility problems. Ioannis is a busy guy, and he says more than once that you are welcome to fork the GitHub repo and send him a pull request.

So Ioannis is ready for you to help out. Beyond this, I have recently learned from Andreas Goser of the German MathWorks office that a team at Volkswagen makes extensive use of this file. According to Andreas, “the app is not yet running on R2014b and higher and [they] contacted the author who said he had no time yet to port it to new MathWorks graphics.”

So there you have it. A cool project, a supportive author, a waiting audience. You’ll fill your brain with new skills and your heart with the gratitude and admiration of your peers.

The project is linked to from the File Exchange, but it lives on GitHub. Time to get busy!

]]>

I want to show you a trick for finding entertaining MATLAB code. Of course I will always recommend that you start looking on the File Exchange or on Sean and Jiro’s awesome Pick of the Week or maybe the MATLAB Examples page. But after that there’s always Google and the great... read more >>

]]>Obviously you can just enter the search term “matlab”, but that mostly returns information about the product rather than what we want: code written by other MATLAB users. To find that, it’s good to know about published M-files. *Publishing* in MATLAB is the process of generating an HTML document that corresponds to your .m script.

There are piles of beautiful published M-files on the web. But how to find them? For this, we will use a special search term. Every published file automatically includes the phrase “Published with MATLAB” at the bottom of the document. So we can search for that term with the help of Google. This pulls in the files we’re looking for as surely as fish on a line.

Search Term: “published with matlab“

I sometimes like to limit my search to files that are not already on the MathWorks site. The advanced Google search directive “inurl” is good for this. If I say “-inurl:mathworks”, then I’ll only get documents that do not have “mathworks” in the URL.

Search Term: “published with matlab” -inurl:mathworks

That’s looking pretty good. Still, it’s a lot of work to sift through these results one by one. I want more immediate gratification! Let’s make it an image search.

Now that’s what I’m talking about! Every single image on the page corresponds to a lovely MATLAB script. Click through and look at a few of them. For instance, maybe I want to take in the Predator-Prey analysis created by Tobias von Petersdorff at the University of Maryland.

Here’s another good one: Yanghong Huang’s page of ODE examples. Yanghong teaches at the University of Manchester in the UK.

Now I want to take things one step further still. Even if you already knew that you can publish from MATLAB scripts to HTML, you might not know this next part. There is a MATLAB command that lets you extract the original MATLAB code from the HTML. It’s called “grabcode”, and it works like this.

>> url = 'http://personalpages.manchester.ac.uk/staff/yanghong.huang/teaching/MATH36032/html/labdemo7.html '; >> grabcode(url)

Now the MATLAB script file has been reconstituted and opened up in an unnamed editor buffer. We can run the code for ourselves in our own MATLAB.

Here’s one last trick. The most recent release of MATLAB (R2016a) includes the ability to create something called a Live Script. It’s a special kind of script that, notebook-style, lets you include both inputs and outputs in the same dynamic document.

If I save the M-file I got from Manchester as labdemo7.m, then in the Current File Browser, I can right-click and open it up as a Live Script.

If I evaluate the resulting document, I’ll see something like this. The new document is nice because, in contrast to the static HTML file, you can do your calculations and coding right in place in the document.

So there you have it. From the world to your doorstep in a few easy steps. Pretty cool, eh?

]]>Cody is a game that rewards you for calculating the same answer with less code. The very first Cody problem you encounter is called Times 2. It’s a starter problem, so it’s meant to be super simple: write a function that multiplies the input by two. As of this writing, something like 17,000... read more >>

]]>function y = times2(x) y = 2*x; end

The size of the code is given by the number of nodes in the code’s underlying parse tree. Without getting into the details of the parse tree, this function has a size of 12. That’s just about the shortest function possible. You might think it’s the very shortest times2 program one could possibly write. Nevertheless, on June 27, 2010, Dirk Engel submitted a solution that decreased the size from 12 to 10.

He wasn’t cheating, and he got the right answer. How did he do it?

You could scratch your head about this for a long time, so I’ll just tell you. Dating back to Cleve Moler’s original version of MATLAB, whenever you don’t specify a left-hand side for a calculation, the result is placed into a default variable called “ans” (for “answer”, get it?). It’s just one of those quirky things that MATLAB does. Here’s where you might see it at the command line.

>> 2*27 ans = 54

Dirk’s solution exploits this feature. It looks like this.

function ans = times2(x) 2*x; end

See what he did there? The result of the calculation is automatically shoved into ans, which happens to be the return variable shown in the function definition. You probably never want to do this with “real” code. But Cody’s just a game, and we’re confident that people know the difference between competitive code-shrinking and wise practice out in the real world.

You can see from the graph that once this trick gets out, it is widely copied. In fact, it shows up all across the Cody site. Dirk himself was a prolific practitioner of the Ans Hack. But he was not, as it happens, the first. That honor goes to the Old Fox, none other than top Cody player and all-around MATLAB virtuoso Alfonso Nieto-Castanon. It first appears in a solution to Problem 495, Formatting Currency Numbers. Alfonso even adds this comment: *“While on the topic of ‘undocumented trivia that will earn you a couple of Cody points for no good reason’, have you seen this one?”*

Let’s turn back to the Times 2 problem. If you look farther along the graph, you’ll notice a curious thing. The Ans Hack appears for the last time on September 2, 2015. Why did it go away? Did the great mass of Cody players, with one collective will, swear off this nasty habit and consign it to the dustbin of history? Nope. In fact, the Ans Hack *stopped working* with the R2015b release, which came out in September of 2015. You won’t find any ans hacks after that.

Actually, that’s not completely true. The ans variable can still be used inside the function. It just can’t be passed out as an output variable. Ugly as it is, this would still work.

function y = times2(x) 2; y = ans*x; end

So it’s still used for point-shaving all over Cody. Just not as an output argument.

But wherever you see an implicit “ans” as the output argument of a passing entry, you can request a re-score and have the satisfaction of seeing it wither from green to red.

**What Do You Think?**

Do you miss this Ans Hack? Do you wish you could get it back? What are your feelings about point-shaving hacks like this? Harmless hackery in the name of good fun? Or a corrosive influence on the impressionable minds of our coding youth? Let me know in the comments!

]]>I saw another fun MATLAB-related tweet go by, this time about soccer rather than doughnuts. The Euro 2016 tournament is going on right now, and José Pedro Silva tweeted a cool MATLAB-generated visualization about passing between the players. This is showing the passing in the Portugal-Iceland match. https://twitter.com/ZPedro10/status/743115988581896192 The game resulted in... read more >>

]]>https://twitter.com/ZPedro10/status/743115988581896192

The game resulted in a 1-1 draw, but just looking at the passing! The line weights show how many more touches Portugal had than Iceland. And indeed, Iceland only managed 28% of possession.

I don’t have access to the fancy code that generated that plot, but I can use this opportunity to show off MATLAB’s graphing capability. Let’s make up some totally random names and passing statistics for a five-man soccer team.

names = { ... 'Lionel Alpha', 'Cristiano Bravo', 'Gareth Charlie', 'Zlatan Delta', 'Sergio Echo'};

Now we can show the edges of the graph: who passed the ball (source), who received it (target) and how many passes they made (numPasses). The number of passes will be assigned to the weight of each edge. So we can see that Alpha passed to Bravo exactly once during the match. Bravo never returned the favor.

source = [1 1 1 2 3 3 3 3 4 4 4 5 5 5 5]; target = [2 4 5 4 1 2 4 5 2 3 5 1 2 3 4]; numPasses = [1 2 1 1 5 2 2 3 2 2 1 4 6 4 8]; weight = numPasses; G = digraph(source,target,weight,names); G.Nodes

ans = Name _________________ 'Lionel Alpha' 'Cristiano Bravo' 'Gareth Charlie' 'Zlatan Delta' 'Sergio Echo'

G.Edges

ans = EndNodes Weight ______________________________________ ______ 'Lionel Alpha' 'Cristiano Bravo' 1 'Lionel Alpha' 'Zlatan Delta' 2 'Lionel Alpha' 'Sergio Echo' 1 'Cristiano Bravo' 'Zlatan Delta' 1 'Gareth Charlie' 'Lionel Alpha' 5 'Gareth Charlie' 'Cristiano Bravo' 2 'Gareth Charlie' 'Zlatan Delta' 2 'Gareth Charlie' 'Sergio Echo' 3 'Zlatan Delta' 'Cristiano Bravo' 2 'Zlatan Delta' 'Gareth Charlie' 2 'Zlatan Delta' 'Sergio Echo' 1 'Sergio Echo' 'Lionel Alpha' 4 'Sergio Echo' 'Cristiano Bravo' 6 'Sergio Echo' 'Gareth Charlie' 4 'Sergio Echo' 'Zlatan Delta' 8

Look how easy it is to make a simple directed graph. Sergio Echo is clearly a passing machine. For Bravo, it was far better to receive than to give.

plot(G,'Layout','circle','LineWidth',G.Edges.Weight,'ArrowSize',15) axis off]]>