In the last few weeks, Sean and Jiro have done some nice posts about File Exchange activity over the years. Sean wrote about top files and authors and then Jiro followed up with most active entries. Jiro’s post reminds me of one I did three years ago on File Exchange... read more >>

]]>Sean’s piece starts off with a file, fx_downloads.xlsx, containing the all-time download counts for every file on the File Exchange. How did he get his hands on that? That information doesn’t appear publicly on the site. Answer: He was able to get it because he has friends on the File Exchange team, and he asked them very nicely.

We do show download numbers on the site, of course, but they’re the download counts for the last 30 days only. From time to time we get this question: why don’t we show the all-time download count for items on the File Exchange? People want to know how they’re doing. They want to have a sense of their impact on the world. They especially want to know how they’re doing relative to other people. We have the data. Why don’t we show it?

Two reasons

**1. MAKE WAY FOR THE NEW (FILES)**

One of the most important ways that people decide if a file is worth downloading is by checking how many times other people have done the same thing. When a site shows all-time download counts, it’s shining a bright light on files that have been around for a long time. If you add a file tomorrow afternoon, you’re going to have a hard time competing with a file that’s been here since 2002. We want to encourage new thinking, new connections, and growth. So we wanted to reduce this strong bias in favor of old files. No matter how well-established your file is, it’s only as good as its track record over the last 30 days. The flip side of this is that, as long as your file is at least 30 days old, you’re on equal footing with every file on the site. Nobody has a baked-in longevity benefit.

**2. GET RID OF THE OLD (DATA)
**

We sometimes notice strange patterns in the download data. There might be unusual spikes of activity that look suspiciously like someone is “helping” their download count with a script. Other times we see extremely odd patterns that don’t look like cheating… they just look like a bot gone wild. For no apparent reason, counts across many unrelated files will balloon one month and calm down the next. To leave in counts resulting from fraud or bot glitches would be misleading. But to carefully remove them from the record would be difficult and expensive. The easiest thing to do is just disregard data that’s older than 30 days. Strange patterns still erupt from time to time, but their influence never lasts more than a month.

It’s not a perfect system, but by showing only the last 30 days’ worth of download data, we make room for cool new submissions, and we avoid the misleading data glitches of yesteryear. So now you know.

]]>Our first interview is with Chad Greene.

Chad has been a top contributor on MATLAB Central since 2012 with his main participation in File Exchange and MATLAB Answers. He is the author of 147 Files on File Exchange, which is a lot. One submission Chad would like you to check out is cmocean perceptually-uniform colormaps

It’s simple, easy to use, and meets a need. The function is aimed at communicating data more effectively, and its implementation is easy to learn and straightforward.

Chad is currently pursuing his Ph.D in Geological Sciences at the University of Texas at Austin. His main focus is in observations of Antarctic ice shelf response to oceanic and subglacial forcing. Basically this means he spends a lot of time researching Antarctica.

Chad was kind enough to let us do a virtual interview.

Chad Greene: When I entered grad school everyone around me seemed to be using MATLAB in their research, and I naturally followed suit.

CG: Both. I was given a project my master’s advisor suggested I do in MATLAB, and that was my first exposure to programming. I found that the more I thought about problems in terms of how I might code them in MATLAB, the better I became as a scientist. Straightforward, repeatable code tends to breed straightforward, repeatable science.

CG: I do receive a fair number of unsolicited emails asking for help. Sometimes folks are thoughtful, personable, and ask interesting questions that challenge my way of thinking–I like that.

CG: I took that at around local midnight at a field site in the middle of West Antarctica. By morning it looked like this

CG: My research group collects data primarily using an old DC-3 airplane which we’ve outfitted with a suite of geophysical instruments. We use lasers to map out the surface of the ice sheet. We use radar to track layers within the ice, and that tells us how Antarctica has changed over many tens of thousands of years. The radar also lets us see what’s happening at the bottom of the ice sheet, which tells us how sensitive an area might be to climate change. And we can learn about past and present geology with data from our magnetometer.

Around Antarctica, half-mile-thick ice shelves the size of US states float over the ocean, and we simply don’t know very much about what’s under there. From our airplane we can measure gravity to such a high degree of precision that we can sense changes in the gravitational pull resulting from deep ocean troughs or high underwater ridges. Knowing where the seafloor is relative to the bottom of the ice gives us an idea of where warming ocean water might flow in and potentially accelerate the ice sheet’s melt rate from below.

While we direct our instruments toward measuring Earth processes, at the same time we’re using Antarctica’s crazy landscape to learn about other icy bodies like Jupiter’s moon, Europa. Ice shelves on Earth are these massive, thick layers of ice that float on the ocean, and it turns out that Europa is covered by a thick layer of ice that floats over its own ocean. The intriguing link here is, we don’t know much about what’s under Antarctica’s ice shelves, but where we’ve looked, even deep under the Ross Ice Shelf, there’s life. So while we’re measuring Earth processes to learn more about the potential impacts of climate change, we’re also developing a radar instrument that will go to Europa. And who knows what we’ll find there.

CG: In the field we primarily use MATLAB for flight planning and preliminary data analysis. The long marathon coding sessions don’t begin until we get back to Austin. Then most of my work involves pairing the laser altimetry data we collect from the airplane, with similar laser data collected by satellites. Getting giant remote sensing datasets working together nicely can present quite a challenge, but there’s a tremendous feeling of satisfaction when you’re analyzing data and you realize you can see processes taking place that no one has ever been able to observe before.

CG: I wrote some flight planning software to help with data collection in Antarctica. It’s absolutely crucial for the safety of my research group’s pilots and engineers to know how much fuel will be consumed on a given flight, how far the plane will be from the nearest safe landing site at any time, and how close the plane might end up flying to rugged mountains in remote regions. My MATLAB flight planning scripts consider topographic features and account for the turning radius of our aircraft when calculating flight lines and estimating fuel consumption.

CG: A few years back I posted some unit conversion functions on File Exchange because after writing them I realized how useful it can be to have simple, intuitive functions to take care of the little stuff. I hoped that by posting my unit conversion functions to File Exchange I might save someone else the trouble of writing similar functions, and that seemed like a net benefit for science.

When I posted my first functions to File Exchange, I didn’t anticipate the benefits of real-time peer review. Pretty soon after posting, I was getting feedback from other File Exchange users who taught me ways to make my codes more efficient.

CG: Documentation. However long it takes to get a piece of code working, spend at least that long writing documentation. It can be a painful process when you’ve finished coding and you just want to be done with it, but you’ll never regret spending the time to write thorough documentation. Documenting is a multipurpose process which serves to teach others, teach your future self, and teach your current self how to use your code. Documenting also helps find errors, identify design weaknesses, and maximize the efficiency of code.

CG: Feedback and understanding. I’ve never taken any courses in programming, so I love getting free lessons from folks who are willing to offer suggestions and share their expertise.

CG: I’d like to see more feedback describing the strengths and weaknesses of a contribution. When I share a function on File Exchange I really like hearing how people are using it, and I like knowing how it can be improved. In the comment section of File Exchange, MATLAB experts have offered me some great advice that has improved my MATLAB skills; but I’ve also benefited from beginners who have identified missing features or unintuitive design in my functions. No matter what your skill level, your feedback is valuable.

CG: My Antarctic Mapping Tools (AMT) project has been a constantly-evolving labor of love for the past few years. I’m proud that I’ve helped strip away some of the technical challenges of working with geospatial data, and as a result I like to think users are able to spend their time on science rather than wrestling with the boring bits of getting different data formats working together. I’m proud that AMT has provided a platform for scientific results to be fully scriptable and therefore fully repeatable, from data importing to data analysis to figure generation.

CG: “Undefined function foo for input type double.” That’s a common error message that pops up frequently in the Answers forum and in File Exchange comments. Sometimes it means the user was trying to call a function that requires a licensed toolbox. Other times it means the function is just in some folder where MATLAB can’t find it.

CG: Many tips and tricks here and there, but the most important concept that’s been ingrained in me is that of the Minimal Working Example. It can sometimes be hard to identify problem lines of code, but it always brings the problem into focus when I go through my code line-by-line, deleting the bits that don’t contribute to the problem. Sometimes that process alone helps me identify the problem before asking for help on the Answers forum. There’s also a broader value in developing an intuition for writing minimal working examples. The ability to isolate relevant processes, to draw direct lines between cause and effect, to communicate clearly and succinctly, and to make results reproducible are all essential to being a scientist.

CG: I stay busy with everything from cooking to woodworking to playing music with friends, but my favorite thing to do? I guess there’s no real joy quite like riding my bike down to the local honky tonk for two steppin’, live music, and whiskey.

Thanks to Chad for taking the time to answer some questions. Be sure to check back for more interesting interviews.

If you have not done so already, please sign up for the 15^{th} Anniversary Celebration for a chance to win some prizes.

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?... 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 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?

]]>