# File Exchange Pick of the Week

## Regexp Builder

Idin's pick for this week is the regexpBuilder by Michael Ryan.

Regular expressions can be a powerful tool in searching through strings or documents. If you haven't used them before, think of them as a string pattern matching tool on steroids.

MATLAB introduced support for regular expressions in MATLAB 6.5 (R13). You can read about regular expressions in MATLAB here. There are also a couple of blog posts on Loren Shure's Art of MATLAB here and here.

Despite their usefulness, the drawback to regular expressions has always been their non-intuitive syntax. For example, how do you find all strings that start with a capital "B" and end with "e"? Here is one option:

regexp('Bobbie was born on Bastille Day before dawn.', 'B[a-z]*e')


Now what if I want to ignore case? Or allow spaces within the string? Regular expressions can handle all these cases, but it takes some experience, and some doing.

Michael's regexpBuilder is an app that allows the user to interactively build their regular expression and see the results in real time. It even has checkboxes for some of the more common tasks (e.g. "ignore case", or "match once"). This can help reduce the time (and frustration) needed to construct the desired regular expression.

The user interface is quite simple: enter the text-to-be-searched in the big "Text" box, then start entering a regular expression in the top left "Regexp" box. The tool displays the results by highlighting and/or underlining the matches in the text window, but it also goes further: it lists all the different outputs from MATLAB's regexp function on the right-hand side of the screen. And just to make things a little more convenient, when you press the "Evaluate" button, it also echoes the equivalent MATLAB command at the MATLAB command prompt.

Suggestions for improvements

This app accomplishes its advertised task quite well. Here are some ideas on what could be added:

• The user interface could be cleaned up to look more professional
• The text boxes on the right aren't supposed to be used by the user, and should probably be locked so the user doesn't type in them.
• Ability to import text files and/or web page would be nice (as in this FileExchange submission).

Get the MATLAB code

Published with MATLAB® R2013b

## Web browser viewable animations

Jiro's pick this week is Web-browser viewable animations by Kevin Bartlett.

I love thinking about creative ways of presenting results. As the number of dimensions increases, I find myself using animation as a way to convey one of the dimensions, oftentimes time. In MATLAB, it's easy to make animations, but when I need to visualize data on a website, I have to get creative. The description Kevin has on his entry page accurately explains the kinds of things I need to be concerned about when creating animations for web pages. To summarize,

• Movie files may not play well in some platforms without an appropriate software.
• Movie files tend to be large, especially when you try to make them cross-platform.
• The image quality may suffer due to video compression.

For these reasons, I often create animated GIF's from my MATLAB visualizations. You can create animated GIF's using the imwrite function. However, Kevin introduces a more elegant, versatile approach of using Javascript to build and incorporate speed and play controls into your animations.

Click on the image below to see an example of a Javascript animation page.

His function has many options to customize the animation and the webpage, including frame delay controls. He provides plenty of documentation and examples to help you use his function.

Give this a try and let us know what you think here or leave a comment for Kevin.

Get the MATLAB code

Published with MATLAB® R2013b

## Easy labeling of a figure or axes

Brett's Pick this week is "Bordertext", by Jan de Wilde.

With "bordertext," Jan has shared an elegant way to label a figure or an axes, saving us the trouble of having to calculate positions for our text. The function takes as an input a string indicating where you want your text. Thus, simply by specifying 'top,' 'bottom,' 'left,', 'right,' 'center', or 'userdefined,' you can position even multiline strings automatically, with respect to the current axes.

Moreover, you can modify those input strings with the prefix 'inner' (in the cases where it makes sense to do so) to make them refer to the interior of your axes, or with 'figure' to make them refer to figure positions. For instance:

modOpts = {'','inner','figure'};
mainOpts = {'topleft','top','topright','right',...
'rightbottom','bottom','bottomleft','left','lefttop','center'};
colors = jet(32);
for ii = 1:15
color = colors(randi(size(colors,1)),:);
modOpt = modOpts{randi(numel(modOpts),1)};
mainOpt = mainOpts{randi(numel(mainOpts),1)};
if strcmp(mainOpt,'center'),modOpt = '';end
option = [modOpt,mainOpt];
bordertext(option,option,...
'Color',color,'BackgroundColor',imcomplement(color), ...
'FontSize',18);
pause(1.5)
bordertext(option,'');
end


Additionally, one can specify a host of formatting commands to control the style of the text.

Jan's code is very nicely written and documented. Plus, I like that he was responsive to a comment requesting support for "standard [MATLAB] syntax." (I garner that the file originally required format strings to be specified in a non-standard fashion. That format option is still available, and convenient, but I agree with the commenter that the standard format is easier to use.)

As always, I welcome your thoughts and comments. Or leave feedback for Jan here.

Get the MATLAB code

Published with MATLAB® R2013a

## INPOLYHEDRON

Sean's pick this week is inpolyhedron by Sven.

### Polygons, Polyhedra and Convexity

It's often useful to know if a point is inside of a polygon (two dimensions) and sometimes if a point is inside of a polyhedron (three dimensions). For two dimensions, MATLAB ships with inpolygon, a nice function to handle this. However, this same operation in three dimensions becomes more complicated. It is simplified if the object is convex. In this case, the vertices can be represented as a set of constraints and we can apply these constraints to the points to test whether they are inside or not. Matt J does this in his vert2lcon function (The runner-up, who will also get some MathWorks swag, for this week's post!).

But what about when the polydehron is not necessarily convex? Now we no longer have this luxury and have to resort to more complex algorithms.

Fortunately, Sven has done the work for us!

% Load shellVertices, shellfaces from Paul's Blog:

% Draw the membrane:
patch('Vertices',shellVertices,...
'Faces',shellFaces,...
'FaceColor','r');
axis tight
view(-51,24)

Add 10000 random points to it

pts = rand([10000,3]); %Generate a random 10000pts
hold on;
plot3(pts(:,1),pts(:,2),pts(:,3),'b*'); %add points to plot

Find the points in the polyhedron

in = inpolyhedron(shellFaces,shellVertices,pts,'FlipNormals',true);
delete(hLine); %clean up
set(hPatch,'FaceAlpha',0.3,...
'EdgeColor','none'); %make the points inside visible

Woohoo!

In addition to everything you saw here, there is also excellent help and many options built into inpolyhedron. Give it a try and let us know what you think here or leave a comment for Sven.

Get the MATLAB code

Published with MATLAB® R2013a

## Colormaps for perceptually challenged individuals

Brett's Pick this week is "Colormaps compatible with red-green color perception deficiencies", by Matthias Geissbuehler.

If you can see a two-digit number in this image, count yourself fortunate:

Most of you will see the "74" in this Ishihara color blindness test image. Others will see a "21." And the significant portion of the population with achromatopsia, a form of color blindness, will see no numbers at all.

Especially if you can see the numbers embedded in the test image, it's easy to forget that many people can't differentiate red from green, and thus can't see them. But we need to keep that in mind when we are creating data visualizations. (I admit that I sometimes forget.)

Matthias's submission addresses this issue nicely, and provides several alternatives for visualizing data with colors designed to facilitate color differentiation by color-deficient individuals.

testim = label2rgb([ones(100) 2*ones(100);3*ones(100) 4*ones(100)],[1 0 0;0 1 0;0 0 1; 1 1 0]);
imshow(testim)

(In case you can't see it, the top left block is red, and the top right is green.)

Now let's redisplay the image using colormaps provided by Matthias's file:

testim2 = rgb2ind(testim,4);
cmap1 = morgenstemning(4);
cmap2 = isolum(4);
cmap3 = ametrine(4);
ax(1) = subplot(1,3,1);
subimage(im,cmap1);title('Morgenstemning')
ax(2) = subplot(1,3,2);
subimage(im,cmap2);title('Isolum')
ax(3) = subplot(1,3,3);
subimage(im,cmap3);title('Ametrine')
set(ax,'xtick',[],'ytick',[])

So, returning to the "74" image, we might, for instance, revisualize it using an "isolum" colormap:

I reduced the image to four colors before creating this colormap. There are options that I haven't tried yet that may well improve this visualization, but I'll leave that to your exploration.

(Note: I recognize that some say that color deficiency is a boon under some circumstances. Colorblind individuals may, for instance, be better able to see objects that are camouflaged to the rest of us.)

At Matthias's request, I'm including a citation to his publication on the topic:

M. Geissbuehler and T. Lasser "How to display data by color schemes compatible with red-green color perception deficiencies" Opt. Express 21, 9862-9874 (2013)
http://www.opticsinfobase.org/oe/abstract.cfm?URI=oe-21-8-9862

As always, I welcome your thoughts and comments. Or leave feedback for Matthias here.

Get the MATLAB code

Published with MATLAB® R2013a

## Schemaball

Sean's pick this week is Schemaball by Oleg Komarov.

I was reading Cleve's post a few months ago about the Lake Arrowhead Coauthor Graph and saw a comment that mentioned an SO thread on schemaballs. This was an interesting read and it was neat to see how this thread inspired the FEX entry.

### Intro to Schemaball

Oleg's schemaball allows you to plot correlation matrices as schemaballs with optional labels and colors. Additionally, it passes back the handles so you can make any other changes after creating it. He provides a good help section and some examples as well as defaults. I also appreciated the "See Also" section where Oleg points to corrplot, a function I'd never heard of before about three minutes ago!

Here, is an example that uses gallery's 'randcorr' option to generate a random correlation matrix:

h = schemaball(gallery('randcorr',18),[],[1 0.25 0; 1 1 0.125],[0.8 0 0.8]);
set(h.l(~isnan(h.l)), 'LineWidth',2)

### MATLAB Unit Testing Framework

The reason I picked this file isn't actually because of the schemaball. Oleg included, along with the schemaball, a schemaballUnit unit testing class that uses R2013a's new MATLAB unit testing framework. Having used this framework a fair amount now, this caught my attention. It was the first (and to my knowledge, only) file on the FEX to use the new framework.

Let's see it in action:

TestSB  = schemaballUnit; %Schemaball test object
Results = run(TestSB)     %Run it and retrieve results
Running schemaballUnit
.
Done schemaballUnit
__________

Results =
TestResult with properties:

Name: 'schemaballUnit/verifyErrorsWarnings'
Passed: 1
Failed: 0
Incomplete: 0
Duration: 0.1482
Totals:
1 Passed, 0 Failed, 0 Incomplete.
0.14818 seconds testing time.


Get the MATLAB code

Published with MATLAB® R2013a

## Line plots with fewer markers

Jiro's pick this week is line_fewer_markers by Massimo Ciacci.

"How can I set the intervals of markers in a plot?"

This is a question that I've seen at various times, both in MATLAB Answers and in MATLAB Newsgroup. The question is in regards to the fact that when MATLAB puts markers on a line plot, it puts them on every data point. For plots with many data points, it becomes visually crowded.

t  = 0:0.005:pi;
plot(t, sin(3*t).*cos(t/2), 'p-')


line_fewer_markers allows you to specify the number of markers to show, regardless of how many data points are plotted.

clf;
line_fewer_markers(t, sin(3*t).*cos(t/2), 10, 'p-');


It has some additional options, such as controlling how the spacing is calculated. This is useful especially when the line is curvey. In such cases, you may want to compute the marker spacing based on the distance on the curve, rather than based on the x distance.

clf;
line_fewer_markers(t, sin(3*t).*cos(t/2), 10, 'p-', 'Spacing', 'curve');


And finally, the function can return a handle that can be used specifically for legend, so that it displays the correct marker and line style.

clf;
h1 = line_fewer_markers(t, sin(3*t).*cos(t/2), 10, 'p-', 'Spacing', 'curve');
h2 = line_fewer_markers(t, -sin(t/2).*cos(3*t), 10, 'o--r', 'Spacing', 'curve', ...
'MarkerSize', 6, 'MarkerFaceColor', 'r');
legend([h1, h2], 'Line 1', 'Line 2', 'Location', 'SouthEast');


Massimo's function is well-documented, and he also includes a few example scripts to show the different use cases.

Get the MATLAB code

Published with MATLAB® R2013a

## August 9th, 2013

Jiro's picks this week are Android Sensor support and iPhone and iPad Sensor support by the MathWorks Mobile Sensor Connectivity Team.

If you own a smart phone, you're probably holding a device with a number of sensors that is constantly collecting information from its surroundings. Many of the apps on your phone make use of these various sensors to operate. Now, you can read from your phone's sensors using MATLAB! If you have R2013a or newer and an Android phone or an iPhone/iPad, you will want to check this out.

After installing a free app for your Android or iPhone/iPad, you can now receive sensor data from you phone directly into your MATLAB session. It is written using MATLAB Classes, and it has a simple interface to read sensor data from your phone.

sensor = sensorgroup('AndroidMobile')

sensor =
sensorgroup logging data from Android device on port 60000

Measurements: (showLatestValues)

Acceleration                        Orientation

Latitude                            Speed
Longitude
Altitude                            MagneticField


Read the latest values from the sensors:

showLatestValues(sensor)

Measurement              Latest Values              Units   Log Size
-------------  ----------------------------------  -------  --------
Acceleration         4.51       -3.30       -8.16  m/s^2    <1x3>
MagneticField   -3.56e-06   -2.49e-05    1.11e-05  Tesla    <2x3>
Orientation         27.08       27.14      -19.39  degrees  <2x3>



Get specific measurements:

sensor.Orientation

ans =
20.6081   34.4375  -15.0781


The entry also comes with a MATLAB app that shows a live view of the data coming in, as well as an example of using the magnetic field information from the phone to rotate a 3D plot.

Get the MATLAB code

Published with MATLAB® R2013a

## Start MATLAB in Last Working Directory

Brett's Pick this week is "Startup MATLAB in Last Working Directory", by Michelle Hirsch.

Several years ago, Loren wrote a blog post encouraging people to share the contents (at least thematically) of their startup files. A lengthy and interesting discussion ensued--it's still worth a read. More recently (last week, in fact!), Sean guest-selected as a Pick-of-the-Week Kevin Bartlett's very useful submission that facilitates the saving of "projects"; I wanted to follow Sean's post with a lighter-weight approach to resuming one's previous coding activities in MATLAB.

When I close MATLAB in the middle of working on a project (or projects), I typically leave relevant editor documents open--whenever it's not inconvenient to do so. That way I can right-click on the tab for an open document and change, relatively painlessly, to its parent directory:

I haven't (yet) implemented Kevin's "projects" approach, but tonight, I changed my long-static startup.m file to incorporate Michelle's "Last Working Directory (LWD)" instructions. Michelle's file contains a small HTML document with instructions--and code snippets--detailing how to modify your startup and finish files to automatically resume working in the directory in which you were last working . It's trivially easy to implement, once you know how, and it saves me the "trouble" of having to manually click to resume my last session.

Also, I'm embarassed to say that, though I've used MATLAB (and 'startup') for nearly 20 years, I never even realized we have a 'finish' file to accompany startup.

As always, I welcome your thoughts and comments. Or leave feedback for Michelle here.

Get the MATLAB code

Published with MATLAB® R2013a

## Save and Load MATLAB Projects in the Editor

Sean's pick this week is Save and load MATLAB "projects" in editor by Kevin Bartlett.

### What is matproj()?

From the help:

matproj.m--Saves and loads MATLAB "projects". A project consists of the
MATLAB files that are currently open in the MATLAB Editor. Loading a
project returns the MATLAB Editor to the state it was in when the project
was saved, with the same MATLAB files open to the same lines, the working
directory set to that of the loaded project and the MATLAB search path
set back to its saved value.

### Why do I like this?

I tend to be a little obsessive compulsive about having many windows open on my computer. This means I close figures, files, Internet Tabs, etc. that I am not using. For the purpose of closing editor files I have a little shortcut, CloseNoPrompt, that allows me to quickly and painlessly close all open MATLAB files.

   function CloseNoPrompt
       %All Editor files;
closeNoPrompt(matlab.desktop.editor.getAll);
   end

matproj allows me to save the current state of my editor so that I can continue to shamelessly close my files but be able to get back to the same state at a later time. This is really useful in day-to-day work where I may need many files open to work on a task but then will not need them for a few days while working on something else. Since matproj also stores the location of the cursor in the file, you can get right back to exactly where you want to be!

### The Gift That Keeps on Giving

I've been trying to break matproj by coming up with edge cases where it might fail. So far, it has outsmarted me every time. Here are a few of the other features that I've run into:

• Works with *.txt, and *.c files as well.
• If a file that is part of a saved project is deleted, it warns that this file is missing and opens the rest of the project.
• If a file is not saved, it stops instead of closing those files.
• Errors if you try to open a file that is not a project.

### Enhancement Requests

My main suggestion to improve this file is to package it into a MATLAB App. This would make it easy to access from the Apps tab. Of course you could add it as a shortcut too.

Okay, I've already turned it into an app and realized it comes with another very nice benefit: The app is now installed in a specific apps directory. Whenever a project is saved or loaded, this directory is the one opened, so the only available *.mat files are ones relevant to this app. This means I don't need to filter through any other ones that may be in the directory.

Another suggestion would be an option to not close all active files when loading a project. Right now, all current editor files are closed when a saved project is loaded. Although this behavior is expected, it would be nice to be able to keep the current files open as well. It would also make it easy to concatenate projects :)

Do you have a use for MATLAB Projects?