This summer my mother-in-law is renting a house on a lake in New Hampshire. Looking at the calendar, my wife said: "The ten-day forecast makes it look like it's going to be pretty hot up at the lake next week." This led to a more general discussion of the merits... read more >>

]]>This summer my mother-in-law is renting a house on a lake in New Hampshire. Looking at the calendar, my wife said: "The ten-day forecast makes it look like it's going to be pretty hot up at the lake next week." This led to a more general discussion of the merits of ten-day forecasts.

It's funny how we can make decisions based on long-term predictions of weather even though we rarely go back and verify that the forecast was any good. Somehow the fact that the forecast exists at all gives it value. I'm left pondering this question: how much should we trust a ten-day prediction? As it happens, I have some data that can be useful here. For some time, I have been collecting some relevant data on Trendy: the ten day forecast for Natick, Massachusetts (hometown for MathWorks). So let's run some numbers.

Here's the trend: Ten Day Forecast Highs for Natick, MA.

Once a day this trend collects ten data points: today's high temperature and the predicted high temperature for the next nine days. In MATLAB, we'll be working with a matrix with one row for each day and ten columns.

Let's get the data into MATLAB so we can play around with it. I can retrieve (and so can you) the data from Trendy as a JSON object using the following call:

http://www.mathworks.com/matlabcentral/trendy/trends/1655/trend_data.json

In order to read this into MATLAB, I'm going to use Joe Hicklin's JSON parser.

```
url = 'http://www.mathworks.com/matlabcentral/trendy/trends/1655/trend_data.json';
json = urlread(url);
raw = JSON.parse(json);
```

t = zeros(length(raw),1); d = zeros(length(raw),10); for i = 1:length(raw) t(i) = raw{i}{1}; predictions = raw{i}{2}; for j = 1:10 d(i,j) = str2num(predictions{j}); end end firstTenRows = d(1:10,:)

firstTenRows = 44 51 59 66 46 48 53 50 51 54 50 58 63 49 48 52 48 46 57 54 59 61 49 47 53 49 48 43 41 48 62 49 48 54 49 39 39 44 47 46 49 48 54 50 40 38 39 47 51 54 47 55 50 39 40 48 52 53 53 53 54 50 40 39 48 53 54 52 52 50 49 40 38 50 55 54 56 56 53 49 40 39 50 56 54 52 56 54 47 43 39 50 55 55 55 59 58 40 41 46

Now I have a temperature prediction matrix that's structured like this.

I want to re-order this matrix so that each line shows the prediction trajectory for a single day in time. That means picking off the diagonals highlighted in the diagram above. So let's write some code that does this shift. I'm going to end up with two new matrices, d1 and d2

rowIndex = 1:10; colIndex = 10:-1:1; sz = size(d); len = (size(d,1)-10); d1 = zeros(len,10); d2 = zeros(len,10); t1 = zeros(len,1); for i = 1:len ind = sub2ind(sz,rowIndex+i-1,colIndex); trend = d(ind); d1(i,:) = trend; d2(i,:) = trend-trend(end); t1(i) = t(i+9); end firstTenRows = d1(1:10,:)

firstTenRows = 54 57 43 39 38 40 39 38 39 39 54 41 44 39 48 48 50 50 50 49 48 47 47 52 53 55 56 55 54 57 46 51 53 54 54 54 55 55 57 58 54 53 52 56 52 55 57 57 60 58 53 52 56 56 59 59 61 63 63 64 50 53 54 58 45 42 45 44 44 43 49 47 40 39 37 42 43 43 43 43 43 41 41 42 44 48 47 49 48 47 46 44 48 49 46 52 51 50 49 48

In d1, each row is the evolving temperature prediction for each day. So when we plot the first row of d1, we're getting the predictive arc for November 13th of last year.

i = 1; plot(-9:0,d1(i,:)) title(sprintf('Predicted Temperature for %s',datestr(t1(i),1))) xlabel('Time of Prediction (Offset in Days)') ylabel('Predicted Temperature (Deg. F)')

In d2, we just subtract from each row the last value in each row. Since this last value is the final (and presumably correct) temperature, this difference gives us the predictive error across the ten days. Here's the error for the November 13th prediction.

i = 1; plot(-9:0,d2(i,:)) title(sprintf('Error in Predicted Temperature for %s',datestr(t1(i),1))) xlabel('Time of Prediction (Offset in Days)') ylabel('Prediction Error (Deg. F)')

Notice that it shrinks to zero over time. That's good! Our predictions get more accurate as we approach the actual day in question. But the early predictions were off by as much as 18 degrees. Is that good or bad? You tell me.

Now let's look at all the days.

plot(-9:0,d2','Color',[0.5 0.5 1]) title('Error in Predicted Temperature') xlabel('Time of Prediction (Offset in Days)') ylabel('Prediction Error (Deg. F)')

It's hard to get a sense of the error distribution. So let's finish with a histogram of the absolute value of the error. Out of 240 measurements in this data set, the median error for a ten-day prediction is six degrees.

hist(abs(d2(:,1)),1:25) title('Histogram of Error in the Ten-Day Forecast') xlabel('Error (deg. F)') ylabel('Number of Samples')

That seems pretty good. Most of the time that error is going to be less than seven or so degrees Fahrenheit (or four degrees Celsius). I probably don't need to pack a sweater for the weekend at the lake.

Get
the MATLAB code

Published with MATLAB® R2014a

Today we have a guest post by Gareth Thomas. Gareth is Academic Marketing Manager for the Education Business in the MathWorks. He aims to inspire people of all ages about technology and share the magic that MathWorks brings to the table when learning, teaching, researching and solving problems that accelerate... read more >>

]]>*by Gareth Thomas*

Today I want to talk about sharing tables in reports (a table is a relatively new data type in MATLAB suitable for column-oriented or tabular data). In the current release of MATLAB (R2014a) it can be a little tricky to represent a table variable in an HTML document. So I’m going to show you how to take the reporting capabilities that MATLAB currently offers, combine them with some HTML 5 and JavaScript, and end up with a beautiful report that functions nicely as a standalone document.

Today there are basically two different ways to create HTML reports from MATLAB.

- MATLAB’s publish command
- The MATLAB Report Generator

The publish command ships with MATLAB, while the Report Generator is a product dedicated to the creation of sophisticated reports from MATLAB. Beyond this, the key difference between the two methods really comes down to when you want to deploy your algorithm. That is, do you want the report to update itself in real time? If you want to create a standalone executable, you can really only use the Report Generator.

I’m going to focus on MATLAB’s publish command. Suppose you want to pass a lot of MATLAB-generated HTML into your published document. It turns out that you can use the disp command to add that HTML code into the generated document. However it is not really easy to pass arguments, as this HTML is hard coded at publish time. To get around this I created a function (makeHTMLTableFilter) that creates HTML code that, when published, is also dynamic and responsive. It achieves this by adding Javascript code. This allows you to do things like filter the table interactively.

See the example below:

This is a very nice way of sharing your results in a form of a table while allowing others to filter the fields that they wish.

One question that I get is, “Okay, but how would I deploy this?” As it happens, this idea of using

`disp(makeHTMLTableFilter(mytable))`

is also supported in the MATLAB Report Generator.

So download makeHTMLTableFilter and give it a try. You’ll soon be making interactive reports of your own.

]]>Here’s a quick post to tell you about a nifty service called Plotly. The basic idea is that you can create nice-looking interactive plots right in your web browser. You can generate the plots using a variety of different APIs and programming languages, one of which is MATLAB. Here’s a quick... read more >>

]]>Here’s a quick example to show you how it works. Let’s suppose you have some data. Say, the per capita consumption of margarine in the US (in pounds). Mmmm. Margarine.

`yrs = 2000:2009;`

margarineConsumption = [8.2 7 6.5 5.3 5.2 4 4.6 4.5 4.2 3.7];

plot(yrs,margarineConsumption)

As soon as you see the margarine data, you think to yourself “Wait a second! Where have I seen that trend before?” A moment of reflection, and suddenly it hits you: Maine divorce rates! That margarine plot is a dead ringer for divorce rates in Maine. Let’s do a plotyy.

`maineDivorceRate = [5 4.7 4.6 4.4 4.3 4.1 4.2 4.2 4.2 4.1];`

plotyy(yrs,margarineConsumption,yrs,maineDivorceRate)

Sure enough, the fit is remarkable*. Now let’s say we want to share our plot as an interactive web page. After adding the Plotly API code to your path, just type

`fig2plotly`

and you get a link to a web page like this:

Cool! Follow the link to try out the interaction.

* The remarkable margarine-divorce correlation was unearthed by Tyler Vigen on his fascinating Spurious Correlations page.

]]>I look up at the sky just after sunset and I see an especially bright star. It's probably a planet. But which one?This question gives me a good opportunity to play around with MATLAB. Let's do a visualization that shows where the planets are relative to the earth and the... read more >>

]]>I look up at the sky just after sunset and I see an especially bright star. It's probably a planet. But which one?

This question gives me a good opportunity to play around with MATLAB. Let's do a visualization that shows where the planets are relative to the earth and the sun. In the process, we'll use JSON services, the File Exchange, MATLAB graphics, and 3-D vector mathematics cribbed from Wikipedia.

Here is the basic grade-school illustration of the solar system, the one that shows the planets rolling around the sun like peas on a plate. For simplicity, we're just showing the sun, the earth, the moon, Venus, and Mars.

But we never see anything like this with our own eyes. Instead, we see bright spots on a dark background somewhere "up there." So let's simplify our problem to determining what direction each naked-eye planet is in. This leads to an image like this.

Our goal is to make an accurate up-to-date version of this diagram. Specifically, relative to the sun, where should we look to find the moon and the naked-eye planets (Mercury, Venus, Mars, Jupiter, and Saturn)? To do this, we need to solve a few problems.

- Find the planets
- Find the unit vector pointing from earth to each planet
- Squash all these vectors onto a single plane
- Visualize the resulting disk

First of all, where are the planets? There's a free JSON service for just about everything these days. I found planetary data hosted on Davy Wybiral's site here:

http://davywybiral.blogspot.com/2011/11/planetary-states-api.html

```
url = 'http://www.astro-phys.com/api/de406/states?bodies=sun,moon,mercury,venus,earth,mars,jupiter,saturn';
json = urlread(url);
```

Now we can use Joe Hicklin's JSON parser from the File Exchange. It returns a well-behaved MATLAB structure.

data = JSON.parse(json)

data = date: 2.4568e+06 results: [1x1 struct] unit: 'km'

The payload is in the "results" field. Each entry has three position components and three velocity components.

data.results

ans = mercury: {{1x3 cell} {1x3 cell}} sun: {{1x3 cell} {1x3 cell}} moon: {{1x3 cell} {1x3 cell}} jupiter: {{1x3 cell} {1x3 cell}} mars: {{1x3 cell} {1x3 cell}} earth: {{1x3 cell} {1x3 cell}} venus: {{1x3 cell} {1x3 cell}} saturn: {{1x3 cell} {1x3 cell}}

The distances are in kilometers, and I'm not even sure how this representation is oriented relative to the surrounding galaxy. But it doesn't really matter, because all I care about is the relative positions of the bodies in question.

Side note: We could also have used the Aerospace Toolbox to get the same information.

`[pos,vel] = planetEphemeris(juliandate(now),'Sun','Earth')`

% List of bodies we care about ssList = {'sun','moon','mercury','venus','earth','mars','jupiter','saturn'}; ss = []; for i = 1:length(ssList) ssObjectName = ssList{i}; ss(i).name = ssObjectName; ssData = data.results.(ssObjectName); ss(i).position = [ssData{1}{:}]; ss(i).velocity = [ssData{2}{:}]; end

% Plot in astronomical units au = 149597871; k = 5; cla for i = 1:length(ss) p = ss(i).position/au; line(p(1),p(2),p(3), ... 'Marker','.','MarkerSize',24) text(p(1),p(2),p(3),[' ' ss(i).name]); end view(3) grid on axis equal

This is accurate, but not yet very helpful. Let's now calculate the geocentric position vectors of each planet. To do this, we'll put the earth at the center of the system. Copernicus won't mind, because A) he's dead, and B) we admit this reference frame orbits the sun.

We're also going to use another file from the File Exchange. Georg Stillfried's mArrow3 will help us make nice 3-D arrows in space.

clf pEarth = ss(5).position; for i = 1:length(ss) % pe = position relative to earth % (i.e. a vector pointing from earth to body X) pe = ss(i).position - pEarth; % pne = normalized position relative to earth pne = pe/norm(pe); ss(i).pne = pne; mArrow3([0 0 0],pne, ... 'stemWidth',0.01,'FaceColor',[1 0 0]); text(pne(1),pne(2),pne(3),ss(i).name, ... 'HorizontalAlignment','center'); hold on end light hold off axis equal axis off axis([-1.2 1.2 -0.8 1.1 -0.2 0.8])

These are unit vectors pointing out from the center of the earth towards each of the other objects. It's a little hard to see, but these vectors are all lying in approximately the same plane.

If we change our view point to look at the system edge-on, we can see the objects are not quite co-planar. For simplicity, let's squash them all into the same plane. For this, we'll use the plane defined by the earth's velocity vector crossed with its position relative to the sun. This defines "north" for the solar system.

pEarth = ss(5).position; pSun = ss(1).position; vEarth = ss(5).velocity; earthPlaneNormal = cross(vEarth,pSun - pEarth); % Normalize this vector earthPlaneNormalUnit = earthPlaneNormal/norm(earthPlaneNormal); mArrow3([0 0 0],earthPlaneNormalUnit, ... 'stemWidth',0.01,'FaceColor',[0 0 0]); view(-45,15) axis([-1.2 1.2 -0.8 1.1 -0.2 0.8])

Now we project the vectors onto the plane defined by earth's motion around the sun. I learned what I needed from Wikipedia here: Vector Projection.

Since we are working with the normal, we are technically doing a vector rejection. Using Wikipedia's notation, this is given by

$$ \mathbf{a_2} = \mathbf{a} - \frac{\mathbf{a} \cdot \mathbf{b}}{\mathbf{b} \cdot \mathbf{b}} \mathbf{b} $$

hold on for i = 1:length(ss) pne = ss(i).pne; pneProj = pne - dot(pne,earthPlaneNormalUnit)/dot(earthPlaneNormalUnit,earthPlaneNormalUnit)*earthPlaneNormalUnit; ss(i).pneProj = pneProj; mArrow3([0 0 0],pneProj, ... 'stemWidth',0.01,'FaceColor',[0 0 1]); end hold off axis equal

We're close to the end now. Let's just calculate the angle between the sun and each element. Then we'll place the sun at the 12:00 position of our planar visualization and all the other planets will fall into place around it.

Calculate the angle between the sun and each of the bodies. Again, from the Wikipedia article, we have

$$ cos \theta = \frac{\mathbf{a} \cdot \mathbf{b}}{|\mathbf{a}||\mathbf{b}|} $$

sun = ss(1).pneProj; ss(1).theta = 0; for i = 1:length(ss) pneProj = ss(i).pneProj; cosTheta = dot(sun,pneProj)/(norm(sun)*norm(pneProj)); theta = acos(cosTheta); % The earth-plane normal vector sticks out of the plane. We can use it % to determine the orientation of theta x = cross(sun,pneProj); theta = theta*sign(dot(earthPlaneNormalUnit,x)); ss(i).theta = theta; end

cla k1 = 1.5; k2 = 1.2; for i = 1:length(ss) beta = ss(i).theta + pi/2; x = cos(beta); y = sin(beta); mArrow3([0 0 0],[x y 0], ... 'stemWidth',0.01, ... 'FaceColor',[0 0 1]); line([0 k1*x],[0 k1*y],'Color',0.8*[1 1 1]) text(k1*x,k1*y,ss(i).name,'HorizontalAlignment','center') end t = linspace(0,2*pi,100); line(k2*cos(t),k2*sin(t),'Color',0.8*[1 1 1]) line(0,0,1,'Marker','.','MarkerSize',40,'Color',[0 0 1]) axis equal axis(2*[-1 1 -1 1])

And there you have it: an accurate map of where the planets are in the sky for today's date. In this orientation, planets "following" the sun through the sky are on the left side of the circle. So Jupiter will be high in the sky as the sun sets.

And that is a very satisfying answer to my question, by way of vector math, JSON feeds, MATLAB graphics, and the File Exchange.

Get
the MATLAB code

Published with MATLAB® R2014a

Two weeks ago we announced that the File Exchange can connect directly to GitHub. Since then, we’ve gotten a lot of great feedback. Here are a few quotes from emails we’ve received… That’s awesome. I was always hoping for that. I just linked my Github Repository to File Exchange :) This is... read more >>

]]>That’s awesome. I was always hoping for that. I just linked my Github Repository to File Exchange :)

This is a nice feature, and thanks for the information. Github is friendly for development and bug fixing and MATLAB Central is professional for publishing MATLAB packages.

This is great news! Updating and maintaining the code was an issue with File Exchange. Thank you for making this connection!

That’s great news and a very logical step towards more open source collaboration in MATLAB. Good job!

Since we launched the feature, we’ve received an average of two GitHub links per day, for a total of 28 repositories so far. Thanks to all of you who have added a link to your GitHub project.

If you want to keep track of the progress, File Exchange guru Josh Natanson has created a trend for it over on Trendy. Watch the number grow! And if you want to see the actual list of GitHUb projects, follow this link:

http://www.mathworks.com/matlabcentral/fileexchange/?term=is_github:true

]]>Let’s say you’ve created an awesome MATLAB file, and you want the world to know about it. So you go to the File Exchange page and click on the big blue button that says “Submit a File”. In the past, you’d see a page that asks you to submit a... read more >>

]]>We’ve added a direct connection between File Exchange and GitHub. In practice, this means that if your code already lives on GitHub, you can leave it there. The File Exchange is now smart enough to distribute the code directly from GitHub to anyone who asks for it from MATLAB Central. You get all the benefits of collaborative development in GitHub while community members get access to the latest version of your projects. No need to maintain the files in two different locations. Push your changes up to GitHub, and seconds later that’s what gets served from the File Exchange.

We’re very excited about this feature, because we know there are already a lot of excellent MATLAB-related repos on GitHub. With this feature, we join two strong communities and open a new era on MATLAB Central.

]]>You’ve probably already noticed the redesigned MATLAB Central Blog site that was released in January. Yesterday, we polished the apple further with an additional release that squashed some bugs and tweaked the look and feel of the site. Since this is the first major overhaul of the Blogs site, we’re all... read more >>

]]>Since this is the first major overhaul of the Blogs site, we’re all pleased to see the new changes released. In fact, we’d like to give you a tour of the Blogs site to show off some of the new features that we’ve added. So sit back and enjoy the view as we take a trip through the new Blogs site.

If you’re a regular reader of the blogs, chances are you haven’t been to the landing page in a while. The last time you went, it probably looked like this:

Now, the landing page looks like this:

In addition to sporting big, colorful images of our bloggers, there are a few other things we’d like to point out:

**Highlights.**The most recent blog posts and Technical Articles are highlighted.**Synopsis.**Mouse over any of the images and you’ll get a brief write-up about the blogger and the focus of their blog. Click and you’ll go to the blog home page, which also happens to be our next stop.

Go to the home page of Loren Shure’s blog, and you’ll see several new features:

**Blog post previews.**Quickly scan through the titles and preview text of the 10 most recent posts by your favorite blogger.**Comments icon.**A lot of posts generate interesting discussions among the readers and many of the bloggers. Just click the gray comments icon next to the title to see what’s going on.**Share a post.**Now you can easily share a blog post with your friends on Twitter, Google+, and Facebook or send them an email link.**Left hand navigation.**This area is chock-full of goodness. Want to find Loren’s 2011 post on Intersecting Lines? Click on the Archive link next to Recent Posts. Interested in reading posts on a particular topic? Check out Categories. You’ll also see Recent Comments and helpful links.

Okay, let’s get to the good stuff and see Loren’s post on Intersecting Lines.

In addition to this terrific post by Loren, you’ll notice a couple of other things:

**Links to the next/previous posts.**Bloggers will sometimes do a series of posts on the same topic. If you liked Loren’s Intersecting Lines posts, you’ll be happy to see at top of the page that she followed it up with a part 2.**Cross blog links.**Perhaps you also enjoy reading Cleve’s posts on scientific computing and interesting mathematics; or Steve’s writings on image processing. Just go to the top of page, click All MathWorks Blogs and go to their home page or their most recent post.

What do you think of the new Blogs site? What do you like about it? What’s still missing? Leave us a comment below.

]]>Are you sad because you can’t play Flappy Bird on your iPhone? We’ve got you covered! File Exchange author Mingjing Zhang has created a MATLAB-based version of the game. Take a look at his other contributions. It’s quite a collection of whimsical MATLAB if you’re in need of a little... read more >>

]]>Flappy Bird is currently the most popular file on the File Exchange, unseating Oliver Woodford’s venerable champion export_fig for the first time in years. How much longer until export_fig is back on top? Or does the ‘Bird have real staying power?

]]>This week’s post comes from Kent Millard, the UX Specialist for the MATLAB Answers team. Quick Answers with Auto-Suggest by Kent Millard Let’s say you’re wondering how to plot some data contained in a 3D matrix. You’ve searched high and low to find an answer, but without satisfying results. Finally, you come across... read more >>

]]>*by Kent Millard*

Let’s say you’re wondering how to plot some data contained in a 3D matrix. You’ve searched high and low to find an answer, but without satisfying results. Finally, you come across the MATLAB Answers page and there it is… the big blue “Ask a Question” button!

With gathering excitement, you press the button and begin to type.

This is where it gets interesting.

Before you even finish your query, similar questions that have already been answered start to appear. One of these might just have the information you need. If so, you get an instantaneous answer pulled from our database of more than 75,000 answered questions!

Here’s how it works.

Start typing your question—keywords or natural language work equally well. The most relevant, answered questions will appear below. The boxes with numbers tell you how many answers there are to a particular question. Green boxes mean the person asking the question confirmed that one of the answers solved their problem.

Questions with tiny blue icons (it’s a stylized MathWorks logo) have been posted by the MathWorks Support Team, and they always include an answer that solves the problem.

We think auto-suggest will save you time. But rather than read more about it, give it a try and tell us what you think!

]]>If you play Cody, you probably already know the name Alfonso Nieto Castañón. He is the number one player by rank, and his answers tend to sprout comments like “Amazing!” and “How did you think of that?!” Alfonso is the guy you want to have in your community. Brilliant, generous, and... read more >>

]]>Alfonso is the guy you want to have in your community. Brilliant, generous, and energetic, he moves through Cody like an artist, insightful answers flying from his fingertips. Through his Cody interactions alone, I suspect he has taught us more MATLAB than many a professor.

He was kind enough to let us do a virtual interview with him. Spoiler alert! In one of his answers he says he solves easy Cody problems while he’s on the phone. I like that. I’m lucky if I can draw a stick man while I’m talking on the phone.

Q: Tell us a little about yourself and your experience with MATLAB. What kind of research do you do and how do you use MATLAB? When did you learn MATLAB? When did you first realize you were a power user?

A: I am a computational neuroscience researcher, and my main focus is on neuroimaging methods. I use Matlab constantly in my research for all sorts of projects. It may be simply using well-established neuroimaging tools (e.g. SPM), developing my own (e.g. Conn), building neural models in Simulink, performing statistical analyses, or even developing real-time speech synthesizers, Matlab is always my first choice. I learned Matlab during my undergraduate studies as a telecommunication engineer, and was quickly won over by the incredible pace at which I could develop a project in Matlab compared to C or other less specialized languages. By the time I was in my graduate studies I was using Matlab almost daily, and I do not believe I have stopped since.

Q: How did you find out about Cody?

A: I was just browsing Matlab Central when I first saw a banner for Cody, and I was quickly hooked by the simple mini-problems, doing “just one more” over and over again. But it was really the wonderful community of users that started growing around Cody what kept me coming back, learning from and being often surprised by other people solutions, and enjoying the continuous stream of imaginative problems that have since then been posted.

Q: You were a champion with the old MATLAB Programming Contest, having won the Grand Prize multiple times. How would you characterize the difference between those two ways of doing competitive coding?

A: Both Cody and the Matlab Contest were fantastic ways of learning from the solutions and the thought-process of others. The old/classic Matlab contest had this fantastic pacing, and a great sense of community (and the rush of last minute solutions!). Cody’s permanence, on the other hand, may miss the rush of a more bounded competition, but it brings in return a never-ending source of enjoyment and learning opportunities. I often find myself revisiting old problems or solutions just to see what other people may have come up with in the meantime, or following specific players just because I enjoy their way of solving problems or because I enjoy the sort of problems that they create. Also the possibility to create your own problems adds a whole different perspective to Cody, and I may have found myself spending way too much time learning the inner workings of Cody just to see “what could be done” with it.

Q: What motivates you to play? Is staying in first place a major factor? Do you watch the leader board to see who’s gaining on you?

A: Not terribly much. It is true that at times I may have gone and solved some perhaps not-terribly-interesting problems just for the thrill of catching that first position, but mostly I come back to Cody looking forward to being surprised by some new problems or solutions, or just staying in touch with the great community here.

Q: How often do you come back? Are you disciplined about your time on Cody, or does it kind take over your schedule at various times?

A: My time on Cody fluctuates a lot, depending on my work or life schedule, but if I am caught up in a series of interesting problems I do have to make a real effort not to let Cody take over too much time from either.

Q: What does a typical session look like for you? When you’re solving a new problem, do you like to get a good answer in quickly and then tune it steadily into a better answer? Or do you like to knock them down quickly and move on?

A: It depends a lot on the problem. There are some interesting problems where I would send one solution after another until I cannot find other ways to “improve” it. Also, when other players are actively sending solutions to the same problems I may get caught in this fun collaboration where we would be trying to build on each other’s ideas. It also depends on the setting, if I am on my phone I may go for simpler or shorter problems, or if I am just relaxing having a coffee perhaps I may take the time to think about some really complex or interesting problem that I read on Cody some time back and never had the time to solve. Last, sometimes I may just feel like revisiting old problems or solutions to see if I can think of a better solution or just wondering what others may have come up with since I last visited them.

Q: What makes a good Cody problem? What are some simple mistakes that problem authors should avoid?

A: For me typically a good Cody problem would have a strong testsuite (avoiding simple look-up table solutions), would not have an immediately obvious “best” way of solving it, and it would not over-engineer the range of expected solutions (e.g. allow some tolerance in error checking, do not forbid or discourage the use of alternative solutions, etc.) Of course I have seen many fantastic problems that break about every of these rules, so new problem creators should probably just follow their instinct and know that their problems will get better with practice. A good place to start is probably to try to find inspiration in the way other people create their problems, I would recommend Richard Zapor, Ned Gulley, Bryant Tran (bmtran), or Tim Vaughan (the cyclist) as some of my favorite problem creators out there. Also I would recommend playing with the format to see what works best. Lately I am increasingly enjoying creating problems that attempt to somewhat explore the limits of what can be done in Cody (e.g. freepasses, Blockland) and, while this might not bring as much fun to others, I am certainly enjoying it! So again, just follow your instincts and experiment a bit.

Q: What makes a good Cody answer? Obviously Cody wants your answer to be short, but beyond that what makes a beautiful answer?

A: The answers I enjoy the most typically would surprise me by using an unexpected approach, some Matlab functionality I never heard of or considered in the context of this problem, or just by virtue of their goofiness or ingenuity.

Q: Do you have any favorite problems or favorite answers you’d like to call out?

A: This would be a very long list. I would say that some of the players who manage to very consistently create solutions that I am sure to enjoy or learn something from are Bryant Tran, with whom I shared the thrill of “discovering” Cody, learning to write highly optimized solutions, and unearthing quite a few hacking tricks, and Tim, who not only creates beautifully efficient code but also he is the one player I can always count on to be able to solve pretty much any problem I throw at him.

Among the problem creators that I enjoy the most I would “special mention” the prolific Richard Zapor (with a ton of fantastic problems in his GJam competition series; his PACMAT series was also ridiculously fun), and Ned Gulley (his problems consistently hit the perfect balance between simplicity of definition, and complexity of possible solutions/approaches; e.g. Remove the air bubbles, Return its own character count, Stride of the longest skip sequence, are really beautiful problems that I often come back to). I also had great fun with Khaled Hamed’s functional programming problems (problems 1198, 1210, 1224), as well as the many hacking problems out there –– starting with Óscar’s “Now!” series (problems 901, 907), Frequency Domain’s “Get me!” series (problems 1745, 1746, 1747, 1752) and my own “Singularity 2.0” series (problems 1769, 1770, 1764).

Q: Can you tell us about some of your back and forth coding with other people? Sometimes it seems like a battle, and sometimes it seems like a conversation.

A: Those sorts of interactions make some of the most memorable moments for me in Cody (and they are always more like conversations or shared experiences, only perhaps disguised as battles). In fact they are probably what have made many of the problems and solutions that I mentioned above particularly meaningful or enjoyable to me. As an example when the “Get me!” series of hacking problems was created it brought together many players trying to find better ways to build strong testsuites that would protect against hacking attempts (and/or find better hacks to break stronger testsuites), and we built from each other’s ideas in what ended up being a remarkable collective experience of discovery. And even though it was somewhat sad to me in the end that we found some sort of all-purpose hack that could not be currently protected against, which unavoidably ended our quest, the entire process was a genuinely fun/bonding/instructive experience.

Q: What are some of your favorite ways to turn a short answer into a really short answer? Do you have any “guilty pleasures” where you know the code won’t win a beauty contest, but it’s great from a Cody point of view? What “tricks” would you recommend to other players?

A: There are a few of these “tricks”. Using command syntax (e.g. print file) instead of function syntax (e.g. print(‘file’)), using str2num to define a “constant” vector or matrix, and the somewhat ugly but necessary ans trick, would probably fall into the “recommendable” category, and they will help you shave a few points of almost any solution. The infamous regexp trick (as well as all sorts of hacking tricks) would probably fall into the “not recommendable” category, as these inevitably flatten the score function (they give any solution, independently of how clever or absurd it is, the exact same score). Despite these tricks, my favorite pleasures really come from finding new simpler ways to approach a problem, or applying some linear algebra tricks, or these sort of discoveries which lead to some small improvements in score in a way that was somewhat unexpected or surprising.

Q: Have you learned anything playing Cody that’s useful to you in your “real world” coding?

A: This would again be a very long list. Most importantly I have widened considerably the range of approaches that I consider now for almost any “real world” problem, but in practical terms I have also learned a lot about regexp functionality, Java usage in Matlab, tricks to speed-up your code, and a lot of new Matlab functionality that I was not aware of (e.g. uint64 operations, timeseries objects, map containers, etc.), just to mention a few examples.

Q: What feature or features would you like to see added to Cody?

A: I believe mostly I would like to better be able to search/browse through old problems and solutions. For example, being able to search problems/solutions that I (or specifically somebody else) ‘liked’ would make the task of coming back to revisit some of the most memorable solutions/problems or discovering new solutions that you may have missed much simpler (in this regard something like a “self-like” marking would be useful, as I would love to hear/follow which of their own problems/solutions some players are most “proud” of).

Q: Do you use any other parts of MATLAB Central?

A: I love the Blogs section (Cleve’s and Loren’s are some of my favorites), very sporadically contribute to the Newsgroup or Answers sections, and have been lately doing my first steps on Trendy (and of course was a big fan of the Matlab Contest).

Q: The most useful MATLAB function that nobody knows about is _______ .

A: accumarray, bsxfun, and cellfun/arrayfun/structfun are incredibly flexible and useful functions that are somewhat underused in my opinion.

Q: If I were a MATLAB function, I’d be _______ .

A: svd (I would spend my day doing linear algebra tricks)

Q: Ramble about anything you want to here…

A: To close I would just like to reiterate how much I appreciate the excellent work of the Mathworks team which makes all of these shared learning and fun experiences possible, as well as to thank the amazing Cody community for sharing so much of their time, brainpower, and humor with the rest of us.

]]>