# File Exchange Pick of the Week

## Surface To Solid

Jiro's pick this week is surf2solid by Sven.

Sven is no stranger to Pick of the Week. His inpolyhedron was Picked by Sean recently, and he's also active in other areas of MATLAB Central. In fact, this entry was inspired by a post written by my colleague Paul on "Printing the 3D L-Shaped Membrane".

3D Printing allows you to easily create 3D objects from a digital model, such as models created in MATLAB. People are already using MATLAB for 3D printing, and we've written about it a few times, including the post above by Paul, as well as "Printing Math" and "Anamorphic 3D Printing".

In order to create a 3D object, we can't print a surface which has no thickness. Paul's post above talks about the process of adding that thickness. Sven took some of those techniques and created surf2solid. It's very easy to use with very good instructions (help). You simply provide the data that you would normally pass into surf or patch, and optionally specify the thickness (for a uniform thickness), the elevation (for a block with a flat bottom), and the triangulation method.

Since I don't have one of those fancy 3D printing machines, I'll show an animation of a vibrating (thick) membrane. This is a modification of a shipping demo called vibes.

% Eigenvalues
lambda = [9.6397238445, 15.19725192, 2*pi^2, ...
29.5214811, 31.9126360, 41.4745099, 44.948488, ...
5*pi^2, 5*pi^2, 56.709610, 65.376535, 71.057755];

% Eigenfunctions
for k = 1:12
L{k} = membrane(k);
end

% Get coefficients from eigenfunctions
for k = 1:12
c(k) = L{k}(25,23)/3;
end

% Construct solids for animation
S = struct('faces',cell(1,500),'vertices',cell(1,500));
x = (-15:15)/15;
t = 0;
for id = 1:length(S)
% Coefficients
t = t + 0.02; % increment time
s = c.*sin(sqrt(lambda)*t);

% Amplitude
A = zeros(size(L{1}));
for k = 1:12
A = A + s(k)*L{k};
end

% Convert SURF data to SOLID data
S(id) = surf2solid(x,x,A,'thickness',-0.1);
end

% Create patch and modify view
pHandle = patch(S(1),'EdgeColor','r');
view(3)
axis([-1 1 -1 1 -.5 1])
axis off

% Animate
for id = 1:length(S)
set(pHandle,'Faces',S(id).faces,'Vertices',S(id).vertices);
drawnow
end


Get the MATLAB code

Published with MATLAB® R2013b

## November 29th, 2013

### Background

This submission contains a suite of tools for getting daily stock prices from Yahoo! and Google. There are utility functions for converting between Yahoo! and Google's formatting and to calculate adjusted closing prices, (which Yahoo! does automatically but which Google does not).

As a side note, Michael Weidman was one of the first few people I met when I started working at MathWorks. He taught me everything I know about the Kolmogorov-Smirnov test ( kstest() ) and was a frequent resource for all of us when it came to math questions (Thanks!). He left MathWorks a little over a year ago to pursue new ventures across the pond.

### Acquiring Financial Data

For this simple example, we will use Michael's tools to pull financial data from Yahoo! and calculate an efficient frontier.

% Selected symbols
symbols = {'TSLA','MSFT','GOOG','MAR','SAM','PG','YHOO'};

% Retrieve data using Michael's function
data = getYahooDailyData(symbols,...
'01/01/2011', '10/31/2013', 'dd/mm/yyyy'); %start, end, format

Data is a struct array of tables!

disp(data)
    TSLA: [730x7 table]
MSFT: [730x7 table]
GOOG: [730x7 table]
MAR: [730x7 table]
SAM: [730x7 table]
PG: [730x7 table]
YHOO: [730x7 table]


The table is a new MATLAB data container in R2013b. Tables make it easy to store heterogenous column data in one container. Michael has included a check to see if the instance of MATLAB is new enough to have tables, if it isn't, the code uses datasets, the table's predecessor from the Statistics Toolbox.

Let's take a look at a table by displaying the first 10 rows of Tesla's data:

disp(data.TSLA(1:10,:));
       Date       Open     High      Low     Close      Volume      AdjClose
__________    _____    _____    _____    _____    __________    ________
7.3451e+05    26.84       27     25.9    26.62     1.283e+06    26.62
7.3451e+05    26.66    26.95    26.02    26.67    1.1874e+06    26.67
7.3451e+05    26.48     26.9    26.19    26.83    1.4467e+06    26.83
7.3451e+05    26.83       28    26.81    27.88    2.0612e+06    27.88
7.3451e+05       28    28.58     27.9    28.24    2.2479e+06    28.24
7.3451e+05    28.17    28.68    28.05    28.45    1.3427e+06    28.45
7.3451e+05    28.59    28.71    26.92    26.96    1.7102e+06    26.96
7.3452e+05    27.01     27.4    26.52    26.96     9.644e+05    26.96
7.3452e+05    26.96    26.97    26.16    26.22     7.236e+05    26.22
7.3452e+05    26.15    26.58    25.61    25.75     1.192e+06    25.75


We can see that the table is displaying the separate variables and their names. The best part is that we can still index it like a matrix using {}.

h = plot(data.TSLA{:,1},...   Date
data.TSLA{:,2:5},... 2nd:5th variables are valuations
'DisplayName',...    Variable names for the legend
data.TSLA.Properties.VariableNames(2:5));

axis tight; % tight axes
datetick('x','mmmyy','keepticks','keeplimits'); %date tick
ylabel('Stock Price (US\$)');

Now that we have the data we can use it to figure out how to get rich quickly by calculating the efficient frontier.

% Extract the closing valuations into an array:
assetsStruct = structfun(@(x)x.Close,data.','UniformOutput',false);
% Uses x.Close to extract the "Close" variable from each table.
assets = struct2array(assetsStruct); % Convert to array

% Convert to returns
assetReturns = tick2ret(assets);

% Create a portfolio object with the asset names. (Financial Toolbox req'd)
p = Portfolio('AssetList',symbols);

% Estimate the asset moments: Mean and Covariance, for the asset returns.
p = p.estimateAssetMoments(assetReturns);

% Set default constraints such that the weights sum up to one and to allow
% long only position (no shorting or shortselling: weights can't be negative)
p = p.setDefaultConstraints;

% Calculate frontier, risk and return
frontierWeights = p.estimateFrontier(20);
frontierRisk    = p.estimatePortRisk(frontierWeights);
frontierReturns = p.estimatePortReturn(frontierWeights);

% Visualize efficient frontier
figure;
plot(frontierRisk,frontierReturns, '*-r','LineWidth',2)
legend('Efficient Frontier','Location','SouthEast')
title('Efficient Frontier');
xlabel('Risk');
ylabel('Return');

### The Rest of It

In addition to giving us easy to use tools to get data from Yahoo! and Google, Michael has also managed to use quite a few of the other features in the MATLAB language. These include: regular expressions, tables, the new functiontests capabilities for running function-based unit tests in the MATLAB unit testing framework, version checking, and safe-guarding against exceptions or errors. For example, when I first ran the above this morning before my laptop had found an internet connection:

### Datafeed Toolbox

For additional options or access to many other popular Financial Data Servers such as Bloomberg® or Thomson Reuters®, MathWorks has the Datafeed Toolbox. This toolbox provides direct access to the servers through their APIs and allows for realtime as well as intraday tick information if requested.

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

Get the MATLAB code

Published with MATLAB® R2013b

## Automatically build MATLAB apps

Jiro's pick this week is App Builder for SimBiology Models by my colleague Asawari Samant.

MATLAB is a scientific software for solving engineering and scientific problems. You can interactively explore your data and apply sophisticated analysis routines to get insights and draw conclusions. Sometimes, you may want to provide those analytical capabilities to other people you work with, but they may not be as familiar with MATLAB as you are. Or, they may not be interested in freely exploring their data, but they would like to be able to apply the specific analysis routines you developed for the problem. In such cases, it's often useful to provide them with a nice user interface around the functionality you built.

With MATLAB, you can create user interfaces for your program, like the one shown below.

But what's different about this app from other MATLAB apps? Well, this was "automatically" created based on a number of parameters.

This entry by Asawari is specifically for users doing PK/PD and systems biology modeling using SimBiology, but a similar framework can be applied to other applications. The basic idea is to create a structure of parameters that defines the SimBiology model that it's connected to, the input parameters that you would like your app to be able to control, the output parameters you want to monitor, and any other parameters that are relevant for the app.

% Project and model information
xin.projectName = 'Tumor_Growth';       % project name
xin.modelName = 'Monotherapy';          % model name

% Inputs and ranges
xin.inputs  = {% Name, Lower Bound, Upper Bound
'L0'  0    20;
'L1'  0    10;
'w0'  0    10;
'k1'  0    20;
'k2'  0    10;
'ke'  0    10;
'x1'  0    10;
'x2'  0    20;
'ka'  0    100;
'Central'  0    10;};    % sliders ranges

% Specify output
xin.outputNames = {% Name , Scope;
'w', ''};            % Name and Scope

% Specify time & time units
xin.timeUnits = 'day';                  % stop time units
xin.stopTime = 30;                      % stop time

% Specify dose properties
xin.doses = 'IV Dose';                  % doses

% Specify name of image file with model schematic
xin.imageFilename = 'tumorModel.png';   % model schematic

% Specify name of the app
xin.appName = 'Model Exploration: Tumor Growth';


Once those parameters are set, you simply call buildApp to create the app.

buildApp(xin, 0)


This framework works really well for this application, because the task of varying parameters and simulating the model is a very common use case in PK/PD modeling. Well, it's common for any kind of modeling for that matter. However, creating a custom app for different models, with different number of parameters, can be a tedious task. Asawari's entry makes this an automated process.

In the entry, Asawari includes several examples that show how one can use the app builder. Note that you need SimBiology and Statistics Toolbox to run this. If you want to create standalone apps, you also need MATLAB Compiler.

If you're doing PK/PD or systems biology modeling with SimBiology, you should definitely check this out. Be sure to let Asawari know what you think. Also, let us know how you create and distribute MATLAB apps to your colleagues, by leaving us a comment here.

Get the MATLAB code

Published with MATLAB® R2013b

## What’s in that MAT File?

Brett's Pick this week is "matwho", by Benjamin Kraus.

Want to know what's in a MAT file without loading it? matwho is for you. Simple, effective, well-implemented, and useful. And fast!

Benjamin's file, which sprang from an interesting discussion on CSSM, provides an easy-to-use wrapper around MATLAB's MatGetDir MEX function. His function is often faster than querying the file with who, but quite honestly, the value of matwho arises from the relative ease of the calling syntax: I have an easier time remembering 'matwho('test.mat')' instead of 'whos('-file','test.mat').

Calling who is pretty darned fast, too...I don't think I would have gone to the trouble that Benjamin did. But I'm glad he did. ;)

Not earth-shattering, but useful nonetheless. And I enjoyed reading through some of the discussion in CSSM on the topic.

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

Get the MATLAB code

Published with MATLAB® R2013b

## RootFinding Demo

Will's pick this week is RootFinding Demo by Teja Muppirala.

Teja is making a comeback after his 2011 Sudoku Pick of the Week. This time, he has created a wonderful little Newton-Raphson app. For anyone who's taken a numerical methods class, you are probably familiar with this technique for finding a value for x that satisfies equation f(x) = 0. But if you're new to the concept, Wikipedia has a great article on the subject.

In essence, this algorithm starts with an initial guess for the value of x. If f(x) equals zero, then lucky you, you're done. If not, you calculate the derivative of the function and use that to aim yourself towards a better guess for the value of x. You repeat this process with your new value of x, and after a few iterations, you hopefully converge on f(x) = 0. In the image below, you see how we approach the zero-crossing of the blue line (our f(x)) with several Newton-Raphson iterations (the red lines).

It turns out that this is a screenshot from Teja's root finding app. The user interface enables you to symbolically express your equation. You specify your initial guess and number of iterations; the app will then present you the solution. What's really fun about this is that you can click on the figure and instantaneously get results for a new initial guess. This interaction is quite instructive in the effectiveness yet limitations of this root finding method. I enjoyed experimenting with functions that weren't continuously differentiable. Oftentimes, my results would be unstable, but every once in a while, I could still achieve convergence.

## Comet3 with Speed Control

Jiro's pick this week is 3D Comet Plot by Nick.

As a continuation to one of my previous posts, on multi-line comet plots, this submission extends comet3 to give the user ability to control the length of the tail, the speed of the animation, and the style of the head and tail of the comet. comet and comet3 are useful functions, because these are functions that take similar type of input as other plotting functions and have animation built into them. I have used both of these functions in the past, but as computers became faster, the animation became too fast to view. That's why I really like the ability of PlotComet_3D to control the speed.

Here's what comet3 looks like.

t = -pi:pi/300:pi;
x = sin(5*t);
y = cos(3*t);
z = t;

comet3(x, y, z)


By using Nick's PlotComet_3D, you can specify the speed in frequency, allowing for a consistent animation regardless of processing speed. Here, I'm also specifying a particular marker for the head of the comet.

% Define marker style for the head of the comet
'Marker', 'p', ...
'MarkerSize', 10, ...
'MarkerEdgeColor', 'b', ...
'MarkerFaceColor', 'b');

% Animate at 100 Hz, tail length of 30
PlotComet_3D(x, y, z, ...
'Frequency', 100, ...
'blockSize', 30, ...


If you have used comet or comet3 in the past and stopped using it because the animation has gotten too fast, give this a try. Let us know what you think here or leave a comment for Nick.

Get the MATLAB code

Published with MATLAB® R2013b

## Visualizing the frequency distribution of 2-Dimensional Data

Brett's Pick this week is "cloudPlot", by Daniel Armyr.

As data acquisition and storage capacities continue to expand, we are constantly being bombarded with increasingly large datasets. Analyzing--or even just visualizing--these data represents one of the most pressing challenges of our time.

Whenever I present "Speeding Up MATLAB Applications," I always make a point of saying that there are "better" (i.e., efficient) ways to use MATLAB, and "worse" (inefficient) ways to use it. (This is true of all languages, of course, but the "cost" of doing things inefficiently in an interpreted language like MATLAB can be more pronounced than when compared with poorly implemented compiled code. I find that people who tell me that MATLAB is slow, often don't use it to its full potential.) I like to make the point, too, that writing better code entails keeping tabs on memory management in addition to performance. (This becomes ever more important with the aforementioned "Big Data challenges.") In fact, one of the topics of that "Speeding Up" presentation deals with efficient visualization of data--and with recognition that visualizations may contain full copies of your data.

Daniel's cloudPlot provides a very clever, and very well implemented, way of visualizing large 2-dimensional data. You can see this clearly in the following code section. First, we create some data. We'll create x and y as 1 million-by-one vectors of normally distributed random doubles; as created, each variable occupies 8 megabytes of memory:

x = randn(1000000,1);
y = randn(1000000,1);


Now how would we best visualize x versus y? We could plot them, of course:

h = plot( x, y, 'b.' );
axis equal
title ( 'Plotting all data' ,'fontsize',12,'fontweight','bold');


As I see it, there are two significant problems with this visualization. First, we have lost all the subtleties of the data. We have a big mass of points, from which we can tell very little about the distribution of our data. And secondly, that graphic contains full copies of x and y! We can see that readily when we get the properties of the plot:

Plotting a small subset--say, 2 percent-- of the data is a good start; we lose very little information, but the plot contains only 300 kilobytes of data instead of 16 megabytes:

pct = 2;
stepsize = 100/pct;
h = plot(x(1:stepsize:end),y(1:stepsize:end),'r.')
title ( 'Plotting 2% of  data' ,'fontsize',12,'fontweight','bold');


However, we still have the significant problem that we can't really tell what's going on with our data.

Enter Daniel's cloudPlot. After cleverly binning the 2-dimensional data, Daniel's function creates a great visualization that yields a lot more information than does the plots we created above:

subplot ( 2, 2, 1 );
colormap(jet);
cloudPlot( X, Y ,[-5 5 -5 5]);
title ( 'Bins exactly one pixel large' );
subplot ( 2, 2, 2 );
cloudPlot( X, Y, [-5 5 -5 5], [], [100 100] );
title ( 'Bins larger than one pixel' );
subplot ( 2, 2, 3 );
cloudPlot( X, Y, [-5 5 -5 5], [], [1000 1000] );
title ( 'Bins smaller than one pixel' );


Now we have a great deal more insight into the distribution of those data. And, the image of the data in the upper left--arguably the most illustrative of the visualizations-- occupies only about a half of a megabyte. (The upper right image is smaller, the lower left, larger.)

Very useful indeed!

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

Get the MATLAB code

Published with MATLAB® R2013b

## Zoomable Text

Jiro's pick this week is TextZoomable by Ken Purchase.

Today's entry was inspired by my colleague, Sean, who also guest posts for this blog from time to time. He and I are application engineers, traveling around the country evangelizing about MATLAB. We once traveled together, and I saw him present a seminar on image processing, which by the way was created by Brett. During the seminar, Sean showed an image that had some annotation to indicate that he was able to successfully differentiate straight lines from curvy lines, just by using image processing techniques. Because the auditorium was pretty big, some of the people in the back had difficulty reading the text. Sean promptly zoomed in using the zoom tool built into the figure.

Then I noticed something. The text became larger along with the image! Later, Sean told me that he was using a File Exchange entry that automatically scaled text when zooming. That was Ken's entry.

In the example below, I have added two text objects, one using MATLAB's text function (red) and the other using Ken's TextZoomable (blue). The syntax is exactly the same as that of text, so it's very easy to swap out the commands.

x  = -pi/2:0.01:pi/2;
y1 = 0.5*tan(0.8*x);
y2 = -0.7*tan(0.8*x);

plot(x, y1, 'b', x, y2, 'r')
xlabel('theta (\theta)')
ylabel('value (\psi)')

text(x(80), y2(80), '\leftarrow \psi = -.7tan(.8\theta)', ...
'FontAngle', 'italic', ...
'Color', 'red');
TextZoomable(x(80),y1(80),'\leftarrow \psi = .5tan(.8\theta)', ...
'FontAngle', 'italic', ...
'Color', 'blue');


Now, if I zoom in (note that you can do this interactively using the zoom tool), the blue text scales nicely with the zoom.

zoom(2)


This is great! This is a must-have for anyone presenting MATLAB graphics with annotation.

Get the MATLAB code

Published with MATLAB® R2013b

## Export to PowerPoint®

Jiro's pick this week is exportToPPTX by Stefan Slonevskiy.

Did you know that you could automatically generate reports from your MATLAB program? You can publish a report in various formats -- HTML, PDF, LaTeX, XML, Microsoft® Word® (only on Windows®), and Microsoft PowerPoint (only on Windows). For PowerPoint output, each section of the program is put into a separate slide, and you can apply formatting afterwards in PowerPoint.

There are a number of File Exchange entries that allow you to programmatically create PowerPoint slides with formatting capabilities, including saveppt (Pick of the Week post), subplotPPT, and officedoc. These entries all use the COM interface to create the PowerPoint document and, therefore, require a Windows platform and PowerPoint. Stefan's exportToPPTX creates the document completely "natively" by creating the necessary XML files and packing them into a PPTX file. That means that this works in any platform that runs MATLAB, and you don't need to have PowerPoint installed. Since this is XML writing, it's much faster than the other COM interface counterparts.

Stefan includes a detailed example that showcases the various formatting options included with the function. As you can see from the animation of the slides below, here are some of the formatting options:

• Setting the size of the slides
• Adding pictures (from figures, axes, image files, CDATA)
• Setting the position and scale of pictures
• Adding text and specifying positions, angles, and font properties
• Adding notes to the slides
• Specifying slide background color.

Do you create presentation slides from your MATLAB results? How do you currently do that? If you haven't used exportToPPTX, give it a try and let us know what you think here or leave a comment for Stefan.

Get the MATLAB code

Published with MATLAB® R2013b

## Easy visualization of volumetric data

Brett's Pick this week is "vol3d v2", by Oliver Woodford.

Today's Pick is brought to you by Oliver Woodford, one of the most popular contributors to the File Exchange, and author of export_fig, the long-time "most-downloaded-file" award winner--itself the recipient of a coveted :) Pick of the Week banner.

When I'm demonstrating the use of MATLAB for image processing, I often show how one can use the output of the isosurface command as an input to the patch command to create easily a rotatable model of a 3D image stack.

>> whos data

Name       Size                   Bytes    Class    Attributes
data       60x256x256             3932160  uint8

white_vol = isosurface(data,2.5);
gray_vol  = isosurface(data,1.5);
figure('renderer','openGL','windowstyle','normal','color','w');
patch(white_vol,'FaceColor','b','EdgeColor','none');
patch(gray_vol,'FaceColor','y' ,'EdgeColor','none', 'FaceAlpha',0.3);


I recognize that that visualization could be improved--there are all kinds of options for controlling the rendering, the lighting, the smoothing, the coloration, etc. But the ease with which MATLAB can create such visualizations impresses me.

Oliver's "vol_3d v2" provides yet another approach to visualization that I will likely be incorporating into my "3D visualization story." With a simple interface modified from the (quite old!) code of fellow MathWorker Joe Conti, Oliver allows us to visualize data, and manipulate its display quite easily:

vol3d('cdata',data,'texture','3D');
view(45,15); daspect(1./voxel_size2); axis tight;axis off;
camlight; camlight(-90,-10); camlight(180,-10);lighting phong;
alphamap('rampup');
alphamap(0.05 .* alphamap);


Oliver writes really nice code, and has the downloads and reviews to prove it. Thanks, Oliver, for this cool submission! (And thank you, Joe, for being amenable to having your code modified and improved by others in the user community. I love to see the File Exchange utilized in this manner!)

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

Get the MATLAB code

Published with MATLAB® R2013b

Brett & Jiro share their favorite user-contributed submissions from the File Exchange.

These postings are the author's and don't necessarily represent the opinions of MathWorks.