Sean's pick this week is ForEach by Jeremy Hughes. My pick this week is a toolbox from our development organization for a foreach loop construct in MATLAB. A foreach... read more >>
]]>Sean's pick this week is ForEach by Jeremy Hughes.
My pick this week is a toolbox from our development organization for a foreach loop construct in MATLAB. A foreach loop allows you to iterate over a set or dimension without having to worry about indexing.
MATLAB actually already has this built in for single elements of numeric arrays:
% Display each element in x for thisfile = [1 pi 8 3] disp(thisfile) end
1 3.1416 8 3
This could've course been written with an index like below.
% Display each element in x with an index thisfile = [1 pi 8 3]; for ii = 1:numel(thisfile) disp(thisfile(ii)) end
1 3.1416 8 3
But what if we want to traverse every column or slice of a three dimensional array? Or each element in a cell array? Or each combination of two arrays? This is where Jeremy's foreach construct comes in handy since you won't need to worry about indexing.
Let's take a bunch of csv files and make copies of them with just the rows of data we care about. These files contain energy outage information for energy outages in America. Being from New England, I just want the records that correspond to the North East.
% Scrape the data directory for all csv files datadir = '.\Data\'; files = dir([datadir '*.csv']); filenames = {files.name}; disp(filenames)
Columns 1 through 4 '2002Data.csv' '2003Data.csv' '2004Data.csv' '2005Data.csv' Columns 5 through 8 '2006Data.csv' '2007Data.csv' '2008Data.csv' '2009Data.csv' Columns 9 through 12 '2010Data.csv' '2011Data.csv' '2012Data.csv' '2013Data.csv'
% Make a directory for output outputdir = 'NorthEastData'; mkdir(outputdir) % Loop over each filename, read, extract, write for thisfile = each(filenames) % Reach each file Temp = readtable([datadir thisfile]); Temp.Region = categorical(Temp.Region); % Convert to categorical % Identify and extract the northeast records northeast = Temp.Region == 'NorthEast'; Output = Temp(northeast,:); % Make new full file name [~,name,ext] = fileparts(thisfile); outputfile = fullfile(pwd,outputdir,[name '_NorthEast' ext]); % Write out writetable(Output,outputfile) end
Now we can check to make sure it did what we expect.
Personally, I see this being really useful for working with sets of files or images, like I have done above, or for needle in the haystack type problems where I want to find something in a bunch of combinations and stop as soon as I do.
And now for a challenge:
I used the informal interface to this toolbox, i.e. the each function, to traverse each file. There is also a formal interface that provides the ability to define your own iterators so that you can traverse objects of your own class or anything else. I will give some MathWorks goodies to anyone who will write their own eachFile iterator that I could use above to recreate what I have.
Please post it below.
The development team is actively looking for feedback on this, so please leave them a comment with any thoughts you have.
Give it a try and let us know what you think here.
Get
the MATLAB code
Published with MATLAB® R2014b
Jiro's pick this week is Decimate Polygon by Anton Semechko. Just a little over a year ago, I wrote a blog post on downsampling polygons. I highlighted Peter's Polygon Simplification. His entry helped me out in one of my side projects I... read more >>
]]>Jiro's pick this week is Decimate Polygon by Anton Semechko.
Just a little over a year ago, I wrote a blog post on downsampling polygons. I highlighted Peter's Polygon Simplification. His entry helped me out in one of my side projects I was working on at the time. Soon after, I received an email from a File Exchange contributor letting me know about another entry for accomplishing the task of downsampling polygons. I appreciate people letting me know about these entries I've overlooked. When I select a file to highlight in my posts I try to do a search on similar entries, but I don't always catch them all.
Let's see how DecimatePoly works. I'm going to use the same image I used for my previous post.
im = imread('amoeba.png');
imshow(im)
As before, I will convert this to black and white and trace out the boundaries using bwboundaries from the Image Processing Toolbox. Then I will overlay the largest boundary onto the original image.
im2 = im2bw(im); boundaries = bwboundaries(~im2,'noholes') largest = boundaries{1}; hold on plot(largest(:,2),largest(:,1),'r','LineWidth',2) hold off
boundaries = [1696x2 double] [ 30x2 double] [ 33x2 double] [ 111x2 double] [ 31x2 double] [ 34x2 double]
Currently, the boundary has 1696 vertices.
size(largest)
ans = 1696 2
With DecimatePoly, I can downsample this polygon by specifying either the maximum acceptable offset from the original boundary or the fraction of the total number of points to retain. For example, if I want to ensure the downsampled boundary to be off by maximum of .1 pixels,
b1 = DecimatePoly(largest, [.1 1]);
# of verts perimeter area in 1695 1948.91 27992.50 out 926 1948.91 27992.50  change 45.37% 0.00% 0.00 %
I can see that I have about 45% fewer points while maintaining the same perimeter and area. If I loosen my constraint,
b2 = DecimatePoly(largest, [1 1]);
# of verts perimeter area in 1695 1948.91 27992.50 out 473 1863.07 28046.00  change 72.09% 4.40% 0.19 %
I have over 70% fewer points while not sacrificing much change in perimeter or area.
figure subplot(1,2,1) plot(largest(:,2),largest(:,1)) axis image ij subplot(1,2,2) plot(b2(:,2),b2(:,1)) axis image ij
So why is having fewer points preferred? Well, Anton has included a nice demo with his entry that shows improved performance in inpolygon tests. This is one of the plots from the demo.
He looked at how different number of polygon points affected the computation time and the accuracy of inpolygon tests. The horizontal axis (Percent simplification) represents the degree of downsampling. The lower the percent simplification, the greater the downsampling. The Dice coefficient (blue) shows how similar the results are between the downsampled polygon and the full polygon. The closer the value is to 1, the more similar the results. The right axis (red) shows the relative speed up of the computation time compared to the full polygon. We can see that even at around 10% simplification (downsampled by 90%), we are able to get over 98% similarity and 10x speed up.
Comments
Do you have a need to downsample polygons? What is your use case? Let us know here or leave a comment for Anton.
Get
the MATLAB code
Published with MATLAB® R2014b
Contact Modeling in SimMechanics Greg's pick this week is Rolling Ball on Plane by Janne Salomäki. Janne put together a nice example of modeling the interaction of a ball contacting a plane, rolling on the plane, and then falling off the plane. Janne uses SimMechanics to model the geometry and motion of the ball... read more >>
]]>
Ccode SFunction 
MATLAB Function 
MATLAB Function (Debugging Disabled) 

2.15 sec 
2.67 sec 
2.30 sec 
~ 
+24% 
+6.8% 
Sean's pick this week is CAD APPS by Larry Silverberg. For this week's pick I'm going to combine my grad school life in structural engineering with the two recent major... read more >>
]]>Sean's pick this week is CAD APPS by Larry Silverberg.
For this week's pick I'm going to combine my grad school life in structural engineering with the two recent major snow storms we've had in New England over the last few weeks. My house has seen about 42 inches of snow. So let's make a quick model of the snow load on my back deck.
I'm going to model this as a Frame. Although it's not an ideal frame by any means, the snow load is distributed on it and not just applied at the ends.
Larry's app allows me to draw the deck interactively (in meters, feet would be nice!)
First I needed to adjust the axes limits:
Next I need to draw the structure. There needs to be a node everywhere I apply a load because there doesn't seem to be a distributed load option. The deck is about 12ft wide with a 3ft cantilever resting about 8ft off the ground.
Then the hard part, figuring out what the load is in terms of Newtons per meter of deck. Being lazy, I only shoveled the outer half of the deck where it was easy to throw the snow off.
psf = 10; % Assume 10 pounds/square foot (lbf/ft^2) width = 2; % 24 inches on center joists = 2ft (ft) ftPerMeter = 3.28; % Feet per meter (ft/m) newtonsPerPound = 0.2248; % (N/m) weightPerMeter = width.*psf.*3.28.*newtonsPerPound; % ft*lbf/ft^2*ft/m*N/lbf = N/m disp(weightPerMeter)
14.7469
And now we simulate and look at the results!
My wood structural design books are somewhere in my attic at home so I have no idea what percentage of capacity the current snow load is using. But with another 6:10in of snow coming Monday, I probably oughtta clear off the rest of it. Sigh.
Give it a try and let us know what you think here or leave a comment for Larry.
Get
the MATLAB code
Published with MATLAB® R2015a
Jiro's pick this week is findInM by our very own Brett Shoelson. If you know Brett, which you probably do if you've spent any time on MATLAB Central, you know about all the useful File Exchange entries he has contributed. It's no... read more >>
]]>Jiro's pick this week is findInM by our very own Brett Shoelson.
If you know Brett, which you probably do if you've spent any time on MATLAB Central, you know about all the useful File Exchange entries he has contributed. It's no surprise he's ranked number 8. Aside from many of the entries related to image processing, he has uploaded a number of utility functions, and findInM is a musthave. The title of the File Exchange entry starts with "FAST, PROGRAMMATIC string searching...", and that's exactly what it is. It searches for a string of text in MATLAB files, but it's fast and it's programmatic. There are already a number of entries in File Exchange that searches for a text within files, including mfilegrep, mgrep, and grep. There is also an interactive way of searching from the toolstrip.
From the description of Brett's entry, findInM "can be much faster than any other method [he's] seen." The way Brett accomplishes this efficient search is by first creating an index of the MATLAB files in the folders. This step takes some time, but afterwards, the search happens on the index file and is very efficient.
In this example, I first created an index of my /toolbox folder (and its subfolders) of my MATLAB installation. Then searching for some text from over 20000 files took less than 10 seconds.
tic s = findInM('graph theory','toolbox') toc
SORTED BY DATE, MOST RECENT ON TOP: s = 'C:\Program Files\MATLAB\R2014b\toolbox\bioinfo\bioinfo\Contents.m' 'C:\Program Files\MATLAB\R2014b\toolbox\bioinfo\biodemos\graphtheorydemo.m' 'C:\Program Files\MATLAB\R2014b\toolbox\matlab\sparfun\Contents.m' 'C:\Program Files\MATLAB\R2014b\toolbox\matlab\sparfun\gplot.m' 'C:\Program Files\MATLAB\R2014b\toolbox\bioinfo\graphtheory\Contents.m' Elapsed time is 8.334972 seconds.
As a comparison, the interactive "Find Files" tool in MATLAB took over 5 minutes to do the same search.
Thanks for this great tool, Brett! I do have a couple of suggestions for improvement.
Comments
Give a try and let us know what you think here or leave a comment for Brett.
Get
the MATLAB code
Published with MATLAB® R2014b
Will's pick this week is Genetic Packman by Hanan Kavitz. Here we have a fun application of genetic algorithms. For those of you unfamiliar, a genetic algorithm mimics evolutionary biology by improving the performance of a population of candidate solutions for a particular problem. Candidates have their "fitness" evaluated by defining... read more >>
]]>Jiro's pick this week is num2words by Stephen Cobeldick. Just recently, I witnessed a typo on a check payment. The amount was for "$19050" (unfortunately, it wasn't for me) but the written text read "One thousand nine hundred ... read more >>
]]>Jiro's pick this week is num2words by Stephen Cobeldick.
Just recently, I witnessed a typo on a check payment. The amount was for "$19050" (unfortunately, it wasn't for me) but the written text read "One thousand nine hundred fifty dollars". Many people might wonder why someone would make such a simple mistake. Did the person miscount the number of zeroes?
I think I have an idea. This was written in Japan. In Japan, and in many other Asian countries, large numbers are grouped in myriads (every 10000). is called man (万), is called oku (億), is called cho (兆). However in Western counting, large numbers are grouped in 1000s  thousand, million, billion, trillion, etc. So, it's likely that the person writing the check wrote "19050", read it as "1 man 9050", and incorrectly translated to "1 thousand 9 hundred 50". Maybe...
Anyway, all of this could have been avoided if this person had access to Stephen's num2words! Just let his function spell out the number in words.
num2words(19050)
ans = nineteen thousand and fifty
This is the simplest use case, but num2words comes with a wealth of options to customize how the results are returned.
num2words(19050,'type','cheque')
ans = nineteen thousand and fifty dollars only
Stephen includes a detailed help in the function, so you can learn about all the options just by typing
help num2words
What gave me a little chuckle was that when I looked inside his function, I could see that he made sure that his function can count up to Uncentillion which is . So if you need to spell out a number larger than , you might be out of luck. :)
Comments
Give this a try, and let us know what you think here or leave a comment for Stephen.
Get
the MATLAB code
Published with MATLAB® R2014b
And so...another year over, a new one just begun.2014 saw some very big changes. MATLAB has changedsubtly. If you haven't tried R2014b yet, try itwe think you'll like it. The new MATLAB Graphics systemlongawaited! is live, and while there may be some growing pains, we're excited about the new things... read more >>
]]>And so...another year over, a new one just begun.
2014 saw some very big changes. MATLAB has changedsubtly. If you haven't tried R2014b yet, try itwe think you'll like it. The new MATLAB Graphics systemlongawaited! is live, and while there may be some growing pains, we're excited about the new things it will enable us to do. In this forum, we welcomed Sean as a lead blogger, and Brett stepped aside to pursue other projects. (He's still around, contributing now and then ;) !)
And once again, the year has seen big growth of MATLAB Central, and lots of big additions to the File Exchange. So without further ado, here is the retrospective of 2014's Picks of the Week.
You can read the original blog posts for each of these picks by clicking on the names of the files and following the links to the "Pick of the Week" tag. As always, your comments are welcome.
Get
the MATLAB code
Published with MATLAB® R2014b
Title/Author/Summary/Notes  Image 

__________________________________________________________________________  
Smooth 3D bezier curves with implicit control points
Uses Hobby's algorithm to plot smooth curves in 3D through specified control points


__________________________________________________________________________  
Sphere Fit (least squared)
Fits a sphere to a set of noisy data. Does not require a wide arc or many points.


__________________________________________________________________________  
Texas Hold'Em Poker Analyzer
Analyzes the win frequency and expected return of a hand in a poker game called Texas Hold'Em.


__________________________________________________________________________  
URL Filter
Scrape one or more numbers off of a web page


__________________________________________________________________________  
International Flight Route Planning Simulator using Aerospace Blockset
Example that shows how you can visualize airline routes on the globe.


__________________________________________________________________________  
Bellagio Fountain Simulation
Simulation of the Bellagio Fountain (100 nozzles)


__________________________________________________________________________  
Polygon simplification
Simplifies a closed polygon by reducing the number of vertices to a specified number


__________________________________________________________________________  
Worker Object Wrapper
Simplifies managing resources such as large data within PARFOR loops and SPMD blocks


__________________________________________________________________________  
Draw a Polar Dendrogram
Draws a polar dendrogram.


__________________________________________________________________________  
Convert seconds to human readable string(s)
Convert an amount of seconds to hours/days/weeks/etc.


__________________________________________________________________________  
Straightforward COPY and PASTE functions
Allows very simple manual exchange with other applications through the clipboard.


__________________________________________________________________________  
Packing Santa's Sleigh
This is the solution by team alfnie to the Mathworks/Kaggle Packing Santa's Sleigh competition


__________________________________________________________________________  
2048 MATLAB Edition
This is a MATLAB implementation of the 2048 game


__________________________________________________________________________  
Communications System Toolbox Support Package for RTLSDR Radio
MathWorks Communications System Toolbox Team Design and prototype softwaredefined radio (SDR) systems using RTLSDR with MATLAB and Simulink


__________________________________________________________________________  
kml2struct
Import a .kml file as a series of shapefile structs. Like kml_shapefile, but more stable.


__________________________________________________________________________  
BOT
Block diagram Optimization Tool


__________________________________________________________________________  
ISSTracker V1.0.0
International Space Station Live Tracking GUI


__________________________________________________________________________  
Wing Designer
Wing Designer computes aircraft performance measures from wing and engine parameters.


__________________________________________________________________________  
Automatic enveloping, variance change and activity detection with Hilbert Transform
Automatic Signal Segmentation and activity detection with Hilbert Transform and smoothing.


__________________________________________________________________________  
cspy.m
cspy: a colorcoded version of sparse matrix viewer spy


__________________________________________________________________________  
MultipleColon
multiple colonintervals


__________________________________________________________________________  
Configurable Simulink Model for DCDC Converters with PWM PI Control
A Simulink model configurable to buck, boost and buckboost DCDC converters with PWM PI control


__________________________________________________________________________  
Useful Figure Management Utilities
3 Useful figure management utilities.


__________________________________________________________________________  
CMEX Programming Tutorial Examples
This submission contains several C scripts that help as an introduction to CMEX programming.


__________________________________________________________________________  
module  encapsulate MATLAB package into a name space module
Modules are handy way to access packages in MATLAB.


__________________________________________________________________________  
legappend
Append new entries to an existing legend


__________________________________________________________________________  
parTicToc
This is a utility for timing PARFOR loops.


__________________________________________________________________________  
ThingSpeak support from MATLAB
MathWorks Internet of Things Team Prototype Internet of Things applications using ThingSpeak and MATLAB


__________________________________________________________________________  
PianoTuner
Graphical aid for tuning the middle octave of a piano


__________________________________________________________________________  
Reference Creator
Find intext citations and create the reference list!


__________________________________________________________________________  
Image Blur Metric
Measure the blur level of still image.


__________________________________________________________________________  
Blind image quality assessment through anisotropy
This measure discriminates blur and Gaussian noise.


__________________________________________________________________________  
Noise Level Estimation from a Single Image
It can precisely estimate noise level from a single image.


__________________________________________________________________________  
Simscape Language: Nonlinear rotational spring (Torque == kx^2)
Simscape language example showing how to use a MATLAB function in the equations section.


__________________________________________________________________________  
SimRF Models of Analog Devices RF Agile Transceivers
Simulate and verify agile RF transceivers and predict impact of RF imperfections using test signals


__________________________________________________________________________  
Colormouse
Mouse control of the color axis


__________________________________________________________________________  
makeinstall
Create a single install file for your toolbox distribution.


__________________________________________________________________________  
Makeinstall Technology
The technology behind the Makeinstall tool.


__________________________________________________________________________  
QuadSim
Parameter driven Simulink model for quadcopter simulation and control system design


__________________________________________________________________________  
Display progress, pause or stop a timeconsuming loop
Allows you to display a loop’s progress, pause (and also change related code) or stop it.


__________________________________________________________________________  
Simulink Dual Gravity Drained Tank
Process control simulation tutorial for PID tuning


__________________________________________________________________________  
votebar
function to plot 'electionlike' 3d bars


__________________________________________________________________________  
Fast Noise Estimation in Images
Estimate the standard deviation of the noise in a grayscale image.


__________________________________________________________________________  
Round with significant digits
Rounds towards the nearest number with N significant digits.


__________________________________________________________________________  
NaturalOrder Row Sort
Naturalorder row sort of a cell array of strings, with customizable numeric format.


__________________________________________________________________________  
NaturalOrder Filename Sort
Naturalorder sort of filenames or filepaths, with customizable numeric format.


__________________________________________________________________________  
Customizable NaturalOrder Sort
Naturalorder sort of a cell array of strings, with customizable numeric format.


__________________________________________________________________________  
Growth  Yet another Obfuscated MATLAB code
Obfuscated MATLAB code where the source looks like its output, with a functional programming demo.


__________________________________________________________________________  
Distribute figures
This function can distribute all open figures on different parts of the screen(s).


__________________________________________________________________________  
Koch curve
Interface for generating the Koch curve

Get
the MATLAB code
Published with MATLAB® R2015a
Jiro's pick this week is "Distribute Figures" by Anders Simonsen. I must be obsessed with figure management, MATLAB figure that is. I've previously Picked three File Exchange entries around this topic: cascade, togglefig, and Useful Figure Management... read more >>
]]>Jiro's pick this week is "Distribute Figures" by Anders Simonsen.
I must be obsessed with figure management, MATLAB figure that is. I've previously Picked three File Exchange entries around this topic: cascade, togglefig, and Useful Figure Management Utilities. No wonder, I was drawn to this entry by Anders.
Have you ever generated lots of figures and wished you could quickly view all of them on one screen?
Anders's distFig lets you do that. Let's say that you have four figure windows.
logo figure surf(peaks) figure plot(rand(10,3)) figure scatter3(rand(50,1),rand(50,1),rand(50,1))
Just call distFig, and it distributes your figures on the screen. Pass in some parameters to control how the figures are distributed.
distFig('Rows',2,'Columns',2)
Anders provides detailed help with the function, as well as some sample code demonstrating the various uses. I also appreciate his responsiveness to user comments. You can see that he quickly updated his entry to fix some issues that came up in R2014b. Great stuff, Anders!
Comments
Give this a try and let us know what you think here or leave a comment for Anders.
Get
the MATLAB code
Published with MATLAB® R2014b