Will's pick this week is Sunrise Sunset by Meysam Mahooti. Ever wonder when the sun is going to set for an event you're planning in the future? Ever wonder when the moon is going to appear above the horizon in the year 2037? Well if so, this is the exchange contribution... read more >>

]]>Ever wonder when the sun is going to set for an event you're planning in the future? Ever wonder when the moon is going to appear above the horizon in the year 2037? Well if so, this is the exchange contribution for you. Meysam predicts the altitude of the sun and moon for a particular point on the Earth's surface. Given a user-supplied date, the code identifies the time of day for sunrise, sunset, dawn, dusk, moon rise and moon set. Here is my the output for yesterday in my home of Columbia, Maryland.

How accurate is the algorithm? It must be pretty good because I found the answer to only be off by a minute for sunrise and sunset when I compared to a weather website. But how will it fare for a future prediction? That depends on the quality of the estimate of the sun and moon's position. The subroutines, SunPos.m and MoonPos.m include perturbation effects of other gravitational bodies, which would be essential for the estimates to remain accurate over a wide range of dates. I had the code estimate times six months from now; sunrise was the same time as the weather site, and sunrise was off by 3 minutes. Not too bad.

A couple things would make this contribution even stronger. First, I would make the main file a function rather than a script so that users can supply different arguments more easily. Second, I'd add more documentation to SunPos and MoonPos so that we could have better insight into the calculations. But still a great contribution...fun and easy to operate.

Let us know what you think here or leave a comment for Meysam.

]]>

Greg's pick this week is Unit Testing C Code using MATLAB and MATLAB Coder by Bill Chou. In general I try to pick entries developed by those outside MathWorks, but... read more >>

]]>Greg's pick this week is Unit Testing C Code using MATLAB and MATLAB Coder by Bill Chou.

In general I try to pick entries developed by those outside MathWorks, but Bill has provided a nice demonstration that combines two topics I'm passionate about: formalize testing and code generation.

Using unit testing in conjunction with MATLAB Coder enables three capabilities:

I recommend taking a look at Bill's videos that go along with this entry.

Fundamentally, a unit test determines if a single feature of software produces expected results under specific conditions. The theory is, by keeping the tests "small" and specific, it is easier to develop and maintain the software and tests.

The primary benefit of having tests is it helps determine if a design meets its requirements. This could apply to the initial design of the software, or when you decide to make changes to the software.

There are all sorts of additional philosophies and techniques that can apply unit testing such as Behavior Driven Development (BDD). I won't get into that here, sufficed to say that how you use unit tests will inform how you write them.

More specifically, there is a unit testing framework available in MATLAB. It is based on the xUnit framework. For those of you who might be stuck on older versions of MATLAB, it's worth checking out this File Exchange entry.

The thing I like about using this the Unit Test framework in MATLAB is it provides a consistent means of defining tests, as well as a number of tools and functions to automate test execution. It also provides a number of levels of sophistication, so if you're not into writing classes and methods to exercise your code, you can use simple scripts or functions instead.

For more about using this framework, I suggest checking out Andy's blog here.

It seems unnecessary and possibly just using a tool because you can.

Well use the right tool for the job. If you want your tests to leverage other MATLAB features that aren't readily available in the language you're using (plotting, filtering, data management), then it may very well make sense to develop your test suite in MATLAB.

In the videos I linked above, Bill does a nice job of going through how to apply the unit tests to the C-code testing process. However, there is an additional benefit for C-code generation from MATLAB that Bill doesn't address directly in the videos for this example.

If you look at the second step of the MATLAB Coder app called "Define Input Types" you will notice that `run_unit_tests` appears in the dialog to "Automatically define input types".

By executing the code found in this dialog, MATLAB Coder can determine what datatype is being used on the inputs to the function for which you are generating code, and apply the appropriate constraints.

In this case you will see that the `addOne` function has an input variable `x` which is a scalar ( 1 x 1) of type `double`.

An example of how to use this feature can be viewed at minute 2:30 of the video here.

Type definition of the inputs is required because C-code is a statically typed language, while MATLAB is a dynamically typed language. (Check out this discussion for more detail about how these type systems differ)

When the unit tests fail, you actually have to look at the test result summary to determine if there was a failure.

To make it more prominent when there is a failure, I recommend throwing an error or assertion if there are any test failures.
I changed `run_unit_tests.m` to the following:

results = runtests( pwd ); if any([results.Failed]) error('Unit test failure'); end

That way, it becomes very obvious that there is an issue to be addressed.

Let us know here.

Get
the MATLAB code

Published with MATLAB® 9.0

Jiro's pick this week is "Command-line peak fitter for time-series signals" by Tom O'Haver.Continuing with the celebration of MATLAB Central's 15th birthday and previous week's blog post by Sean, I'd like to focus on all of the great interactions people have had through the File Exchange entries. Although, you may... read more >>

]]>Jiro's pick this week is "Command-line peak fitter for time-series signals" by Tom O'Haver.

Continuing with the celebration of MATLAB Central's 15th birthday and previous week's blog post by Sean, I'd like to focus on all of the great interactions people have had through the File Exchange entries. Although, you may not think of the File Exchange as the next big social network, people have collaborated and exchanged conversations through the comments and rating sections of the entries. When I see a File Exchange entry with a lot of comments, I tend to think that the file is getting a lot of interest from other users. If I also see a lot of responses from the author of the file, that means that the author is actively involved with improving and helping people use the file. If there are a lot of updates to the entry, that also means that the author is actively maintaining the file.

So, I wanted to see which files had the most interactions amongst the author and the users. *Disclaimer: Not all of the metrics used here are purely quantitative. I've introduced some qualitative fudge factors.*

**The Data**

I gathered my data the brute-force way, of course using MATLAB. I went through all possible File Exchange IDs and scraped each webpage for comments and updates.

```
load FEX
```

Here's what the first few entries look like.

FEX(1:5,:)

ans = Name FEXID Author Comments Updates _________________________ _____ ____________________ ___________ ___________ 'central_diff.m' 12 'Robert Canfield' [3x4 table] [5x3 table] 'interpsinc.m' 13 'Michael Minardi' [1x4 table] [1x3 table] 'Polybase' 15 'Giampiero Campa' [8x4 table] [7x3 table] 'Toolbox BOD Version 2.8' 16 'Gert-Helge Geitner' [1x4 table] [7x3 table] 'connectnames.m' 17 'Douglas Harriman' [1x4 table] [0x3 table]

Here are the comments from the first entry (central_diff.m, which was Picked a couple of weeks ago).

FEX.Comments{1}

ans = Date Name Comment Rating __________ ___________________ _____________________________________________________________________ ______ 2004-09-16 'godlove njie teku' ' ' 4 2006-08-09 'Shyang-Wen Tseng' '<p>This is a very good and usefull add-on function. Thank you.</p>' 4 2007-08-06 'Alvaro Valcarce' '<p>I think that line 98 should be (notice the "=" sign)</p>…' 4

And the updates for that entry.

FEX.Updates{1}

ans = Date Version Description __________ _______ __________________________________________________________________________ NaT '' '<p>update description</p>' NaT '' '<p>description</p>' NaT '' '<p>updating description</p>' 2001-08-21 '' '<p>updating</p>' 2015-10-01 '2.0' '<p>Second-order accurate forward and backward difference formulae are u…'

**The Metric**

To help me find the entries with the most "interactions", I first calculated the number of comments and updates from the data.

FEX.NumComments = cellfun(@height, FEX.Comments); FEX.NumUpdates = cellfun(@height, FEX.Updates);

Next, I also wanted to know of all the comments for each entry, how many were by the author of the entry.

```
FEX.NumAuthorComments = cellfun(@(a,c) nnz(strcmp(a,c.Name)), ...
FEX.Author, FEX.Comments);
FEX.NumUserComments = FEX.NumComments - FEX.NumAuthorComments;
```

**Most Comments**

Let's see which entry had the most comments.

FEX = sortrows(FEX,'NumComments','descend'); barh(FEX.NumComments(10:-1:1)) title('Number of Comments') % Truncate the file names to the first 20 characters (for labeling) fexNames = cellfun(@(x) x(1:min(20,length(x))),FEX.Name(10:-1:1),'UniformOutput',false); % Axes properties ax = gca; ax.YLim = [0 11]; ax.YTickLabel = fexNames; ax.TickLabelInterpreter = 'none'; ax.YTickLabelRotation = 30;

Not surprisingly, `export_fig`.

**Most Updates**

How about most number of updates?

FEX = sortrows(FEX,'NumUpdates','descend'); barh(FEX.NumUpdates(10:-1:1)) title('Number of Updates') % Truncate the file names to the first 20 characters (for labeling) fexNames = cellfun(@(x) x(1:min(20,length(x))),FEX.Name(10:-1:1),'UniformOutput',false); % Axes properties ax = gca; ax.YLim = [0 11]; ax.YTickLabel = fexNames; ax.TickLabelInterpreter = 'none'; ax.YTickLabelRotation = 30;

"DICOM to NIfTI converter" just beats `export_fig`.

**Highest percentage of comments by the original author**

One way to see how much the original author was involved with the user comments is to look at the percentage of author comments. (Yes, an author can be heavily involved without actually responding to comments on the File Exchange. He/she can choose to respond via email or simply update files.) To account for bias towards low number of comments, I have included an arbitrary qualification cutoff of 20 comments.

FEX.AuthorCommentRatio = FEX.NumAuthorComments ./ FEX.NumComments; % Fix 0/0 (-> NaN) to 0 FEX.AuthorCommentRatio(isnan(FEX.AuthorCommentRatio)) = 0; % Only look at entries with 20 or more comments FEX = FEX(FEX.NumComments >= 20,:); FEX = sortrows(FEX,'AuthorCommentRatio','descend'); FEX(1:5,{'Name','Author','NumComments','NumAuthorComments','NumUpdates'})

ans = Name Author NumComments NumAuthorComments NumUpdates ___________________________________ _________________________ ___________ _________________ __________ 'ipf(arg1,arg2,arg3,arg4)' 'Tom O'Haver' 23 14 39 'nth_element' 'Peter Li' 26 14 7 'Tree Controls for User Interfaces' 'Robyn Jackey' 29 15 6 'Wavelet Based Image Segmentation' 'Ashutosh Kumar Upadhyay' 23 11 16 'iPeak' 'Tom O'Haver' 36 17 30

Great job folks!

Let me add another arbitrary qualification cutoff of 10 minimum updates.

FEX = FEX(FEX.NumUpdates >= 10,:); FEX(1:5,{'Name','Author','NumComments','NumAuthorComments','NumUpdates'})

ans = Name Author NumComments NumAuthorComments NumUpdates __________________________________________________ _________________________ ___________ _________________ __________ 'ipf(arg1,arg2,arg3,arg4)' 'Tom O'Haver' 23 14 39 'Wavelet Based Image Segmentation' 'Ashutosh Kumar Upadhyay' 23 11 16 'iPeak' 'Tom O'Haver' 36 17 30 'Command-line peak fitter for time-series signals' 'Tom O'Haver' 120 54 41 'Fast Bilateral Filter' 'Kunal Chaudhury' 20 9 14

Wow, Tom is up there 3 times!! I'm a little intrigued by the 4th one, which has 120 comments with 41 updates. Let's take a closer look at the timings of those comments and updates.

% Process the 4th entry % Break up the comments into user comments and author comments authorCommentID = strcmp(FEX.Author{4},FEX.Comments{4}.Name); userComments = FEX.Comments{4}(~authorCommentID,:); authorComments = FEX.Comments{4}(authorCommentID,:); % Create plot h1 = scatter(datenum(userComments.Date),ones(1,height(userComments)),... 'MarkerFaceColor','b','MarkerEdgeColor','none','MarkerFaceAlpha',0.25); hold on h2 = scatter(datenum(authorComments.Date),1.5*ones(1,height(authorComments)),... 'MarkerFaceColor','r','MarkerEdgeColor','none','MarkerFaceAlpha',0.25); h3 = plot([FEX.Updates{4}.Date FEX.Updates{4}.Date]',... repmat([0;0.5],1,height(FEX.Updates{4})),'Color',[.3 .7 .3],... 'DatetimeTickFormat','uuuu'); hold off % Axis properties ax = gca; ax.YLim = [0 2]; ax.YTick = [1 1.5]; ax.YTickLabel = {'Users','Author'}; ax.YTickLabelRotation = 60; ax.YGrid = 'on'; title({FEX.Name{plotID},FEX.Author{plotID}}) ylabel('Comments') xlabel('Date') legend([h1;h2;h3(1)],'User Comments','Author Comments','Updates')

We can see that there is a nice balance of comments from users and Tom. The updates seem to be coming in at a nice regular interval, with updates happening recently. This is a sign that Tom has been heavily involved with interacting with users and keeping the file up-to-date.

Thank you, Tom, for being a great citizen of MATLAB Central and the File Exchange! You are what makes this community thrive.

**Comments**

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

Get
the MATLAB code

Published with MATLAB® R2016a

Sean's going to take this week to celebrate the top files and authors of the File Exchange. As you may know by now, MATLAB Central is celebrating its 15th birthday.... read more >>

]]>Sean's going to take this week to celebrate the top files and authors of the File Exchange.

As you may know by now, MATLAB Central is celebrating its 15th birthday. Let's start by making it a File Exchange based birthday cake!

HappyBirthday({'MATLAB' 'Central'}, 15)

I figured an interesting thing to look at would be the top files of all time and the distribution downloads based on the total number of downloads for each file.

T = readtable('fx_downloads.xlsx'); T = sortrows(T,'total_downloads','descend');

And the 15 most downloaded files are:

barh(T.total_downloads(1:15)); ax = gca; ax.YTickLabel = T.title(1:15); ax.YDir = 'reverse'; ax.XAxis.Exponent = 0; ax.YAxis.TickLabelInterpreter = 'none'; xlabel('Total Downloads') title('Top 15 Files')

It's not a surprise to me at all to see `export_fig` at the top. We'll dig into it a bit more later. There are also three Arduino support packages up there. This isn't too
surprising either given the popularity of Arduinos in recent years.

What about the distribution in number of downloads of all of the files? Let's look at a histogram of the number of files binned by number of downloads. Note, the log scale.

histogram(T.total_downloads, [logspace(0,5,30) inf]) set(gca, 'XScale', 'log') xlabel('Total Downloads') ylabel('Number of Files') title('Download Distribution')

So which authors have the most files and downloads?

Sum the total number of downloads grouping by author.

Author = varfun(@sum,T,'GroupingVariables','Creators_name','InputVariables','total_downloads'); summary(Author)

Variables: Creators_name: 10468x1 cell string GroupCount: 10468x1 double Values: min 1 median 1 max 189 sum_total_downloads: 10468x1 double Values: min 1 median 1154 max 6.9059e+05

So it looks like there are 10468 unique authors. Most people submit only one file and one person has submitted 189 files. Who's that?

disp(Author(Author.GroupCount == 189,:))

Creators_name GroupCount sum_total_downloads ________________________ __________ ___________________ 'Antonio Trujillo-Ortiz' 189 3.7709e+05

What does the distribution of submitted files per author look like?

histogram(Author.GroupCount) set(gca,'XScale','log') axis tight xlabel('Number of Files') ylabel('Number of Authors') title('Number of Files per Author')

What about the most downloaded author?

Author = sortrows(Author,'sum_total_downloads','descend'); barh(Author.sum_total_downloads(1:15)); ax = gca; ax.YTickLabel = Author.Creators_name(1:15); ax.YDir = 'reverse'; ax.XAxis.Exponent = 0; ax.YAxis.TickLabelInterpreter = 'none'; xlabel('Total Downloads') title('Top 15 Authors')

So what about `export_fig`? It used to belong to Oliver Woodford, the original author. In August 2015, Yair Altman took over maintenance and ownership
of it. It's only fair that we give Oliver credit for the years he owned it.

I have another file that has export_fig's history. Read it in convert the date to datetime for logical indexing and plotting. The original format was 'yyyyMmm', e.g. 2016M07 for July, 2016.

HistoryExportFig = readtable('monthly-export_fig_Downloads.xlsx'); HistoryExportFig.MonthName_Download = datetime(HistoryExportFig.MonthName_Download,'InputFormat','yyyy''M''MM'); summary(HistoryExportFig)

Variables: MonthName_Download: 88x1 datetime Description: Original column heading: 'Month Name - Download' Values: min 01-Apr-2009 median 16-Nov-2012 max 01-Jul-2016 SourceFileId: 88x1 double Description: Original column heading: 'Source File Id' Values: min 23629 median 23629 max 23629 FileDownloadCount: 88x1 double Description: Original column heading: 'File Download Count' Values: min 555 median 2163.5 max 4082

How has `export_fig` been used with time?

plot(HistoryExportFig.MonthName_Download, HistoryExportFig.FileDownloadCount) Aug15 = datetime(2015,8,0); hold on h = plot([Aug15 Aug15],ylim); legend(h,'Yair Takes Over','location','northwest') xlabel('Time') ylabel('Monthly Downloads') title('Monthly Export Fig Downloads')

So it looks like `export_fig` use is in decline. But don't worry, I don't think it's Yair's fault! MATLAB R2014b included a new graphics system in MATLAB.
With this printing has become much improved which has removed usecases where `export_fig` really helped; for example, with antialiasing. As users migrate to newer releases, I'd expect to see this trend continue.

So what happens if we give Oliver credit for the `export_fig` downloads leading up to August, 2015?

% Sum the file downloads before ownership transferred beforeAug15 = HistoryExportFig.MonthName_Download < datetime(2015,8,18); export_fig_Oliver = sum(HistoryExportFig.FileDownloadCount(beforeAug15)); % Add it to Oliver's count idxOliver = find(strcmp(Author.Creators_name,'Oliver Woodford')); Author.sum_total_downloads(idxOliver) = Author.sum_total_downloads(idxOliver)+export_fig_Oliver; % Re-sort Author = sortrows(Author,'sum_total_downloads','descend');

Is it enough to bring Oliver into the top 15?

idxOliver = find(strcmp(Author.Creators_name,'Oliver Woodford')); disp(['Oliver''s ranking: ' num2str(idxOliver)])

Oliver's ranking: 23

Not quite, but it brings him from 129th down to 23rd!

What has been your "Top File" ever? Is there any other way you'd like me to slice this data? Let us know here!

Get
the MATLAB code

Published with MATLAB® R2016a

Jiro's pick this week is Teaching Calculus with MATLAB by the TCM Team.I really like these apps that the folks from TU Darmstadt and University of Stuttgart created for teaching various calculus concepts. Many concepts taught in calculus can can be better understood if the students can visualize them. Back... read more >>

]]>Jiro's pick this week is Teaching Calculus with MATLAB by the TCM Team.

I really like these apps that the folks from TU Darmstadt and University of Stuttgart created for teaching various calculus concepts. Many concepts taught in calculus can can be better understood if the students can visualize them. Back when I was in college, I remember learning the Newton's Method on paper, drawing tangent lines iteratively to find a root of a function. Just the fact I could draw (visualize) the process made it easier to understand.

It would be even better if I could repeat this learning experience for an arbitrary function. Using interactive apps like the ones the TCM Team made improves the experience greatly.

Here are a couple of other examples, polynomial interpolation and steepest descent.

In addition to the pure usefulness of these apps in teaching situations, here are my other reasons I like this submission.

- Well-written MATLAB code. All of the apps are written in a consistent manner, making use of nested functions to share two common structures across the app, one for maintaining the data specific to the concept and another for the user interface. Well-written code means maintainable code.
- Similar UI for all apps. Because all apps look similar with similar set of buttons and parameters, it's easy for you to use any of the other apps once you learn to use one.
- Because of points 1 and 2, the team can easily create other apps for other concepts, which they intend to do in the future.

**Comments**

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

Get
the MATLAB code

Published with MATLAB® R2016a

In honor of MATLAB Central's 15th anniversary this week, Sean's picks this week are the two "oldest" files on the File Exchange. Contents ... read more >>

]]>In honor of MATLAB Central's 15th anniversary this week, Sean's picks this week are the two "oldest" files on the File Exchange.

Every File Exchange entry has an id that you can reference it with. These ids continue to increase as new files arrive on the File Exchange with the 58671st arriving just now.

Thus is seems that the "first" file on the File Exchange might be the one with the lowest id. I did a quick binary search typing in URLs with low ids and discovered that 12 was the lowest index on the File Exchange. At one point, there was a file at 11, but it has since been deleted.

So what is file 12? It's central_diff by Robert Canfield. This file was originally submitted on October 27th, 2000 and actually most recently updated, last year or 15 years later, to make it more accurate!

This file computes the derivative of a vector using a second order central difference. Here's a quick example:

x = linspace(-2*pi,2*pi,1000); f = sin(x); dfdx = central_diff(f,x); plot(x,y,x,dfdx) axis tight xlabel('x') legend({'$f(x)$', '$\frac{dF}{dx}$'}, 'Interpreter', 'latex')

But is it really the oldest?

There are different ways to sort results on the File Exchange and one is by *"Date Submitted (Oldest - Newest)"*.

Looking at the oldest one, it's routh by Edmundo Rivera-Santos. This file has an index of 58 but was submitted on January 30, 1997!

It seems this is truly the oldest file. And it still runs almost two decades later in R2016a!

**NOTE** There is no BSD license so use at your own risk.

syms a b c EPS ra=routh([1 a b c],EPS)

ra = [ 1, b] [ a, c] [ -(c - a*b)/a, 0] [ c, 0]

It's also great that both of these files happen to have the characteristics of a pick of the week. They have good: help, error checking, comments and examples which I'm sure have been used hundreds or thousands of times over the years.

So why does routh precede central_diff in age but not index? I reached out to Ned to find out.

Before there was a File Exchange, there was an FTP site where files could be shared. Ned provided this antique screen shot of that FTP site; the files were in the "contrib" folder:

When the File Exchange was created, the FTP files were not immediately migrated. Thus the first files posted to the File Exchange got lower ids.

Give them a try and let us know what you think here or leave a congratulatory comment for the authors of routh or central_diff.

Get
the MATLAB code

Published with MATLAB® R2016a

Sean's pick this week is Chebfun - Current Version by the Chebfun Team. My pick this week is the current version of Chebfun. Some of you may be thinking:... read more >>

]]>Sean's pick this week is Chebfun - Current Version by the Chebfun Team.

My pick this week is the current version of Chebfun. Some of you may be thinking: "You're repicking it, it's already been picked" and discussed on Cleve's blog! This is sort of true; the previous version of chebfun was picked and is still available.

But I'm not going to spend my time trying to show you great examples or talk about the usefulness of this tool. The chebfun team already has a great example gallery, which is very similar to the MathWorks example gallery, that covers the vast range of capabilities.

I'm going to discuss the conversation I had with Professor Trefethen, the inventor of Chebfun, at the annual SIAM conference in July, 2016. He approached me at the MathWorks booth and wanted to know why the older version continues to see so many downloads when they're trying to encourage users to migrate to the new one? Here's a screenshot of the current downloads:

As you can see over the last 30 days (August 9, 2016), the old version has 41 downloads compared to 68 for the new one. But it clearly says "Please download current version". The description on the file's page repeats this and points at the new one and the chebfun website. Professor Trefethen was curious what could be done to migrate more people to the current version. The challenge is that he'd like the older version to remain available for people who intentionally need backward compatibility but not for any new users.

I suggested that the older code and example files be removed from the File Exchange and replaced with a readme that points to the current version. After some explaining the enhancements and fair warning, the readme would then have a link to where the old one could be downloaded be it the chebfun website or github.

Backward compatibility is obviously a challenge for the File Exchange. The integration with GitHub has helped but for files not linked to GitHub it can be difficult to impossible to get older versions of code when a file is updated.

What are your thoughts on the idea of a readme, multiple versions of a tool on the File Exchange, and the importance of backward compatibility on the File Exchange? Is this a challenge you've struggled with?

We also discussed content curation on the File Exchange. There currently is none outside of ensuring export control compliance. Do you think that content on the File Exchange should be curated in some way?

Give the latest version of chebfun a try and let us know what you think here or leave a comment for the Chebfun Team.

Get
the MATLAB code

Published with MATLAB® R2016b

Sean's pick this week is Questdlg Timer by Az Nephi. Contents Background ... read more >>

]]>Sean's pick this week is Questdlg Timer by Az Nephi.

My colleague approached me last week to ask about having a `questdlg` time out after a certain period of time. His use case was that he wants to ask end users about some database settings before changing
them. However, if there's no person there, which there may not be if it's running in a scheduled environment or if the person
is busy, after a set period of time, pick the default and keep going. Here's the question he was asking:

So what's the challenge? The `questdlg` is a modal dialog box meaning execution of the command line, script, or function, is held until the dialog is closed. This means that
I can't programmatically close it after a `pause`.

So the first thing I did was search the File Exchange and MATLAB answers. The File Exchange didn't turn up anything promising (searching for "timeout") and MATLAB answers had a few questions where this was asked.

Obviously, I could build the whole thing from scratch, but that seems like a lot of overhead. Instead, I'll use a `timer` which emulates a second thread and fires periodically after an optional delay.

- The
*'StartDelay'*will be the timeout. - The
*'TimerFcn'*will close the modal figure. - By default, timers only fire once.

We'll build and start the timer, then build the `questdlg`. Additionally, tic and toc are around the question dialog to see that it times out.

t = timer('StartDelay',10,... 'TimerFcn',@(~,~)delete(findall(groot,'WindowStyle','modal'))); start(t) tic answer = questdlg('Do you want to use the ODBC driver?','Driver','ODBC','JDBC','Cancel','ODBC')

answer = 0×0 empty char array

toc

Elapsed time is 10.037885 seconds.

I'd now have to test if *answer* is empty and define it to be the default if it is. Challenge complete!

So then I was going to polish this idea and push it to the File Exchange but figured I'd search a little more first. This time, I searched for "questdlg".

Face palm!

Thanks Az, you wrote exactly what I needed! And it is much simpler, Az just modifed the call to `uiwait` to use the built in *'timeout'* option.

answer = questdlg_timer(10,'Do you want to use the ODBC driver?','Driver','ODBC','JDBC','Cancel','ODBC')

answer = 1×4 char array ODBC

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

Get
the MATLAB code

Published with MATLAB® R2016b

Jiro's pick this week is smoothn by Damien Garcia.As the title of Damien's entry states, smoothn is a fast and easy smoothing function for n-dimensional data. It uses a generalized cross-validation method to estimate the smoothing parameter, which affects the quality of the output. In layman's terms, it automatically does... read more >>

]]>Jiro's pick this week is `smoothn` by Damien Garcia.

As the title of Damien's entry states, `smoothn` is a fast and easy smoothing function for n-dimensional data. It uses a generalized cross-validation method to estimate the smoothing parameter, which affects the quality of the output. In layman's terms, it automatically does things for you so that you just pass in the noisy data and out comes the smoothed data. Damian includes links to two of his papers for technical reference for those interested in the detailed theory.

From what I've seen, his code is very well written (Code Analyzer is green!), with plenty of error-checking and good use of vectorized code. It has extensive help, and he includes many different types of examples. Here is one that I liked.

**Noisy image with missing data**

Filling in missing data in an image?! What?!

n = 256; % Original image y0 = peaks(n); % Noisy image with missing data y = y0 + randn(size(y0))*2; I = randperm(n^2); y(I(1:n^2*0.5)) = NaN; % lose 1/2 of data y(40:90,140:190) = NaN; % create a hole % Smoothed image z = smoothn(y); % <-- That's all!! % View subplot(2,2,1:2) imshow(y,[]) title('Noisy corrupt data') subplot(2,2,3) imshow(z,[]) title('Recovered data ...') subplot(2,2,4) imshow(y0,[]) title('... compared with the actual data') colormap(parula)

**Comments**

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

Get
the MATLAB code

Published with MATLAB® R2016a

Contents Hardware Support for Image Aquisition from Kinect v2 Using the Kinect for Windows v2 in MATLAB Initializing the device Get a 3-D point cloud from the device Viewing the point cloud stream from the Kinect v2 Detect planes in the 3-D point cloud Release the device Avi's pick of the... read more >>

]]>colorDevice = imaq.VideoDevice('kinect',1) depthDevice = imaq.VideoDevice('kinect',2)

colorDevice = imaq.VideoDevice with properties: Device: 'Kinect V2 Color Sensor (kinect-1)' VideoFormat: 'BGR_1920x1080' ROI: [1 1 1920 1080] ReturnedColorSpace: 'rgb' ReturnedDataType: 'uint8' DeviceProperties: [1x1 imaq.internal.DeviceProperties] depthDevice = imaq.VideoDevice with properties: Device: 'Kinect V2 Depth Sensor (kinect-2)' VideoFormat: 'Depth_512x424' ROI: [1 1 512 424] ReturnedColorSpace: 'grayscale' ReturnedDataType: 'uint16' DeviceProperties: [1x1 imaq.internal.DeviceProperties]

step(colorDevice); % Initialize color/RGB sensor step(depthDevice); % Initialize depth sensor colorImage = step(colorDevice); % Load one color/RGB frame depthImage = step(depthDevice); % Load one depth frame

ptCloud = pcfromkinect(depthDevice,depthImage,colorImage);

player = pcplayer(ptCloud.XLimits,ptCloud.YLimits,ptCloud.ZLimits,... 'VerticalAxis','y','VerticalAxisDir','down'); xlabel(player.Axes,'X (m)'); ylabel(player.Axes,'Y (m)'); zlabel(player.Axes,'Z (m)'); % Then stream a live 3-D point cloud from the Kinect v2. for i = 1:500 colorImage = step(colorDevice); depthImage = step(depthDevice); ptCloud = pcfromkinect(depthDevice,depthImage,colorImage); view(player,ptCloud); end

colorImage = step(colorDevice); depthImage = step(depthDevice); ptCloud = pcfromkinect(depthDevice,depthImage,colorImage); % Grab a new point cloud maxDistance = 0.02; referenceVector = [0,0,1]; maxAngularDistance = 5; [model,inlierIndices,outlierIndices] = pcfitplane(ptCloud,maxDistance,referenceVector,maxAngularDistance); figure; pcshow(ptCloud); hold on; plot(model)

release(colorDevice); release(depthDevice);]]>