Jiro's pick this week is Reference Creator by Valerio Biscione. Even though I have been away from the world of academia for quite some time, I can remember and appreciate the effort that people put into writing... read more >>

]]>Jiro's pick this week is Reference Creator by Valerio Biscione.

Even though I have been away from the world of academia for quite some time, I can remember and appreciate the effort that people put into writing papers. And in that process, one of the more mundane tasks is putting together the references. Not only do I need to figure out the exact article and journal names, I need to put the information in the correct format. It may not be super difficult, but it's definitely time-consuming.

Valerio's Reference Creator makes this process extremely easy. It accesses Mendeley, an online research paper database, to gather the bibliographical data based on some search criteria, such as author name and year. You can use his tool either through the command line interface or the UI. I gave it a try using a paragraph from one of my papers.

It even gave me a warning when it found multiple matches with the same author(s) and year.

Thanks Valerio for this useful tool! I'm sure a lot of researchers out there will appreciate this.

*Warning: This entry uses some undocumented/unsupported capabilities, namely the displaying of colored and bold text in the
edit boxes. Use this entry with caution, as undocumented features can change in behavior or stop working at any time.*

**Comments**

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

Get
the MATLAB code

Published with MATLAB® R2014a

Will's pick this week is Piano Tuner by John Bender. If you want the distinguished honor of a Will Pick of the Week, here are some easy guidelines to follow: Choose an interesting or fun topic. Package the submission so that it's easy to figure out how to use. Ensure that it actually works... read more >>

]]>If you want the distinguished honor of a Will Pick of the Week, here are some easy guidelines to follow:

- Choose an interesting or fun topic.
- Package the submission so that it's easy to figure out how to use.
- Ensure that it actually works for standard user inputs.

I'll probably want to get a second opinion, but PianoTuner tells me that my keys are all falling flat. As to how it figures this out, the algorithm is about 80 lines of code embedded into the UI callback functions. It looks like there's a fast Fourier transform and a polynomial curve fit in there.

Incidentally, you can run the tool against non-piano instruments as well. I played a random song on my computer speakers and found that musicians with professional instruments do much better.

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

]]>

Sean's pick this week is ThingSpeak Support for MATLAB by MathWorks' Internet of Things Team. Contents ... read more >>

]]>Sean's pick this week is ThingSpeak Support for MATLAB by MathWorks' Internet of Things Team.

Up until recently, I'd heard the phrase the "internet of things" thrown around only a few times and didn't really know what it meant. So I spoke with our Marketing Manager for the Maker Movement, Paul Kassebaum, to get a better understanding. Paul describes it briefly as "The confluence of technologies in communication (the internet as we know it), the energy internet (or energy from sensors, etc.) and the logistics internet (the ability to use this information for logistics)."

This week's pick uses all three. It allows you to pull data directly into MATLAB from ThingSpeak, a platform and cloud service where data can be uploaded from sensors and low cost hardware. After pulling this data, you can use it for whatever research, design or logistics you want.

I saw this blog post on our Maker Zone blog that described measuring soda consumption here at MathWorks. They posted the file on the FEX as well.

This made a challenge for me: Could I gather a few people together, drink as much Powerade as possible at 4pm Eastern Time on August 5th, and create an outlier data point?

We had a few detractors, like Loren, who did not properly appreciate the health benefits of this type of social gathering.

To passerbyers, it probably looked like we were part of some obscure MATLAB cult. Let's see how we did:

% Grab the data for July 6th through August 6th. [drinkData, timeStamps] = thingSpeakFetch(7040,'DateRange',{'06-July-2014','06-August-2014'}); Powerade = drinkData(:,3); % Third channel is Powerade % Index into the party hour idxParty = hour(timeStamps)==16 & day(timeStamps) == 5 & month(timeStamps)==8;

scatter(timeStamps(idxParty),Powerade(idxParty),400,'MarkerFaceColor',[0.03 0.6 0.8],'MarkerEdgeColor',[0.03 0.6 0.8]); hold on scatter(timeStamps,Powerade,15,'MarkerFaceColor',[0.5 0 0],'MarkerEdgeColor',[0.5 0 0]); datetick('x','mmmdd','keepticks','keeplimits'); legend('Powerade Party','Powerade Consumption','location','northwest')

So it does look like we were able to create a Powerade Consumption outlier. Go Team!

Give it a try and let us know what you think here or leave a comment for our Internet of Things team.

Get
the MATLAB code

Published with MATLAB® R2014a

Sean's pick this week is Par Tic Toc by Sarah Wait Zaranek. I run a fair number of computationally expensive operations and often use parallel for (parfor) loops to speed... read more >>

]]>Sean's pick this week is Par Tic Toc by Sarah Wait Zaranek.

I run a fair number of computationally expensive operations and often use parallel for (parfor) loops to speed them up. This utility interested me mainly because it shows how work is distributed across the workers and provides worker utilization rates.

First, I will make sure a parallel pool is open using `gcp()` or "Get Current Pool". This opens the headless MATLAB processes that a parfor loop distributes iterations to.

pool = gcp

pool = Pool with properties: Connected: true NumWorkers: 2 Cluster: local AttachedFiles: {} IdleTimeout: 90 minute(s) (89 minutes remaining) SpmdEnabled: true

We'll do a simple example with a loop that has a random pause. The pause is a proxy for an operation that takes a varying and unpredicable amount of time.

n = 50; p = Par(n); % Build the Par timer parfor ii = 1:n Par.tic; % start timer pause(randi(5)) % Pause for up to five seconds p(ii) = Par.toc; % measure elapsed time end stop(p); % all done plot(p);

The parfor loop has done a good job distributing the calculations between the two workers. The more highly utilized worker only has one additional iteration that the other.

There are a few other neat tricks in here as well that I found from looking through the code.

- If you right click on the axes with each iteration's time, it gives you context menu to select the scale.
- Since the Par class inherits from handle, you get those visible methods. Sarah hides those from
`methods()`by making their signature hidden. - Sarah has also provided a full set of documentation on the capabilities of this utiltiy as well as examples.

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

Get
the MATLAB code

Published with MATLAB® R2014a

Jiro's pick this week is legappend by Chad Greene. Chad is no stranger to MATLAB Central. He has over 50 File Exchange entries, and two of his entries have been highlighted (unit converters and ccc) in Pick of the Week. His entries... read more >>

]]>Jiro's pick this week is `legappend` by Chad Greene.

Chad is no stranger to MATLAB Central. He has over 50 File Exchange entries, and two of his entries have been highlighted (unit converters and ccc) in Pick of the Week. His entries are well-written, and like this one, many of his entries have published example files.

Many of you may know that the command `legend` creates one legend per axes.

t = 0:.1:10; x1 = sin(t); x2 = cos(t); plot(t,x1,t,x2) legend('Sine','Cosine')

Let's say that you wanted to add another line to this plot.

x3 = sin(t).*cos(t); hold on plot(t,x3,'--r')

To add this entry to the legend, you would re-run the `legend` command with the three entries.

legend('Sine','Cosine','Sine*Cosine')

Chad's `legappend` allows you to append new entries to an existing legend. This means that you can simply call it along with the new lines you
create.

% New figure figure; plot(t,x1,t,x2) legend('Sine','Cosine') % Add another line hold on plot(t,x3,'--r') % Append a new legend item legappend('Sine*Cosine')

Great! You can also delete the last legend entry with the following command.

`legappend('')`

If you want to see more examples, check out his published example.

Chad explains that `legappend` simply deletes the current legend and recreates the updated legend. This is a good example of how you can take a normal mode
of operation and tweak it in order to adapt it to your needs.

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

Get
the MATLAB code

Published with MATLAB® R2014a

Greg's pick this week is module - encapsulate MATLAB package into a name space module by Daniel Dolan. The concept of namespaces has been available in MATLAB for a number... read more >>

]]>Greg's pick this week is module - encapsulate MATLAB package into a name space module by Daniel Dolan.

The concept of namespaces has been available in MATLAB for a number of years at this point. While the technology is very mature at this point, a common feature of namespaces was not included in the MATLAB implementation. You cannot call one function in the same namespace from another function in the same namespace without including the namespace definition somewhere. Most namespaces in other languages permit functions to call each other within the namespace without needing to identify the namespace.

Daniel’s “MODULE” function provides an interesting means to work around that constraint using a method that demonstrates the powerful concept of function handles in MATLAB.

The nature of Daniel’s solution also provides a means to create namespace specifiers, without needing to continually reference the full namespace.

Finally Daniel makes it possible to have what one might call “dynamic namespaces”.

I selected this submission because it demonstrates the powerful feature of function handles, advertises the use of namespaces in MATLAB, and uses the “DBSTACK” function in a way that surprised me.

Yes, it happens. There’s what appears to be a bug in this File Exchange submission. Change line *110* from

`root=sprintf('%s.',root{:});`

to

`root=sprintf('%s.',root{end:-1:1});`

The order in which package namespaces is being constructed is backward. Changing this line reverses the construction and resolves the issue.

If you’re not familiar with namespaces, don’t fret. It is an advanced software engineering concept. I work with a lot of software engineers all over the world, and many of them are not familiar with namespaces because they work in coding languages or environments that don’t have them (such as C).

A namespace provides a means to specifically call unique functions that share the same name. I like to think of a namespace as a context or a classifier for a function.

Let’s say you have two functions, each named “myDisp”, but they have different behavior.

`>> myDisp('Hello')`

My Display 1 Hello

Versus

`>> myDisp('Hello')`

My Display 2 ------------- Hello

How do you invoke the appropriate *myDisp* at the correct time?

Perhaps you could give the functions different names: *myDisp* and *myDisp2*.

But if you’re concerned about modularity, and these functions are used independently in other projects and code files, changing the name of the functions will be problematic.

What if instead you could include an identifier that would make the call to the *myDisp* function more specific?

>> myFirstNamespace.myDisp('Hello') >> myOtherNamespace.myDisp('Hello')

Now both functions can be available, without introducing a name conflict, or needing to change the name of the function.

To accomplish this in MATLAB, you need to use package folders

While namespaces provide a means to be more specific about function calls, they can be inconvenient when it comes to actually writing them out, and reading them in the code file. Especially as the namespaces get longer.

`>> myMainNamespace.myOtherSubNamespace.myOtherNamespace.myDisp('Hello')`

This seems hard to read, and a pain to write.

We can use the IMPORT function to handle this:

```
>> import myMainNamespace.mySubNamespace.myFirstNamespace.*
>> myDisp('hello')
```

My Display 1 Hello

Now contents of the myFirstNamespace can be referenced without using the full namespace notation. But if you import two functions with the same name but live in different namespaces, you are back to the same problem that namespaces try to solve! You can partially import namespaces, but this gets tedious.

The MODULE function makes it possible to refer to functions in namespace by essentially providing an alias for the namespace. This means you can refer to functions deep within a namespace without needing to write out the full namespace, or have the potential conflict issues using the IMPORT function.

>> myLocalSpace = module('myMainNamespace.mySubNamespace.myFirstNamespace'); >> myLocalSpace.myDisp('Hello')

>> myOtherLocalSpace = module('myMainNamespace.myOtherSubNamespace.myOtherNamespace'); >> myOtherLocalSpace.myDisp('Hello')

Here the calls to the functions in the namespace are concise and specific to the desired function.

This also allows you to do fun things like make the namespace dynamic

if (a < b) myLocalSpace = module('myMainNamespace.mySubNamespace.myFirstNamespace'); else myLocalSpace = module('myMainNamespace.myOtherSubNamespace.myOtherNamespace'); end myLocalSpace.myDisp('Hello')

I cannot say at this point whether or not having dynamic namespaces is a good idea, but it is certainly an interesting concept.

In MATLAB, if a function in a namespace calls another function in the same namespace, it must refer to the full namespace of the function being called.

function myDisp( displayInput ) displayHeader = myMainNamespace.myOtherSubNamespace.myOtherNamespace.otherFunction; disp(displayHeader); disp(displayInput); end

This is fine, until later when you wrap the existing namespace in another parent namespace, and you must go into all of the functions and append the new parent namespace. If you have hundreds of functions, this is going to get old fast.

Daniel provides a really neat mechanism to get around this constraint. Calling MODULE with no inputs assumes the namespace you want is relative to the current function.

function myDisp( displayInput ) localNamespace = module; displayHeader = localNamespace.otherFunction(); disp(displayHeader); disp(displayInput); end

Now, even if the structure of the namespace changes, you can still call the functions local to the namespace, because the
local namespace is automatically updated when the *myDisp* function is called.

This is the part I think is really elegant.

In order to make this work, Daniel takes advantage of function handles. Function handles are pointers or aliases to functions. This means you can use a variable to store a reference to a function.

Daniel creates a collection of these function handles by creating function handles for each of the functions in a specific package folder. Then he stores these function handles in a MATLAB struct. Subreferencing the struct using the dot notation (struct.field) will now act like referencing a function in a namespace. How cool is that!

Finally, to get around the constraint MATLAB imposes of functions in a namespace referencing other functions in the same namespace, Daniel uses the DBSTACK function.

I’m pretty sure he’s using DBSTACK in a way it was never intended, but I think it’s absolutely brilliant!

Daniel uses the DBSTACK function to determine what function called MODULE, so he can then figure out what namespace the function belongs to.

While there may be some performance implications from using DBSTACK, it is an excellent demonstration of the flexibility of the MATLAB environment. You can ask a function “Who called you?” I’ve been working with MATLAB over 15 years now, and I didn’t realize you could do that!

If you would like to leave any comments regarding this post, please click here.

Get
the MATLAB code

Published with MATLAB® R2014a

Sean's pick this week is "C-MEX Programming Tutorial Examples" by Ilias Konsoulas. I spent the last few days at the 2014 SIAM conference in... read more >>

]]>Sean's pick this week is "C-MEX Programming Tutorial Examples" by Ilias Konsoulas.

I spent the last few days at the 2014 SIAM conference in Chicago manning the MathWorks booth with a few of our developers. We were asked many questions about the products, new features, life at MathWorks, and of course for t-shirts and rubik's cubes.

One of the questions I was asked was along the lines of: "How do I get started with MEX?". MEX, which is short for "MATLAB Executable", is compiled C/C++ or Fortran code with the appropriate MATLAB wrappers on it so that it can be called at the command line like any other MATLAB function. Personally, I haven't written any productive C/C++ code since high school about ten years ago. When I need C or C++ code, I develop the algorithm in MATLAB and then use MATLAB Coder to automagically generate equivalent C code.

I had found Ilias' submission a while ago and added it to the "to experiment with list". Now, it allowed me to answer this question while sounding knowledgable and getting the user started on his journey.

The submission comes with nine heavily commented C files that do simple matrix manipulations like summing and reshaping as well as a readme file that documents the package. The C files show the MEX syntax, required headers and some good programming practices like error checking.

Curious if I could actually write my own hand-written MEX file, I challenged myself to write one which calculates the sum
of the diagonal of a matrix. I started by editing Ilias' `transposeM.c` which should be a good blueprint.

After some time, having it fail to compile 20ish times, and getting stuck in an infinite loop only once(!), (I forgot to increment
*i* in the `for`-loop), it works!

Here's a snapshot of the file:

That was an exercise in frustration. How about we just use MATLAB Coder to do this? First, I wrote a MATLAB function to
calculate the sum of the diagonal; there happens to be a function called `trace` that does this:

Now to generate C code, you can use the MATLAB Coder App to generate code interactively, or do it programatically with `codegen`. I'll take the latter approach since it's easier to automate.

% Input must be a double precision matrix of size "up-to-inf" by "up-to-inf" input_specs = coder.typeof(zeros,inf,inf); codegen mytrace -args {input_specs}

This generates `mytrace_mex` which I can call like any other function.

rng(5) % reproducible X = gallery('randhess',7); % a matrix t = mytrace_mex(X); % use mex file disp(t)

-0.1573

Now let's see if the two C implementations and the MATLAB implementation agree using the MATLAB unit testing framework.

% Build interactive test object Tester = matlab.unittest.TestCase.forInteractiveUse; % Assert equality assertEqual(Tester,trace(X),traceM(X)) % My C implementation assertEqual(Tester,trace(X),mytrace_mex(X)) % MATLAB Coder's implementation

Interactive assertion passed. Interactive assertion passed.

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

Get
the MATLAB code

Published with MATLAB® R2014a

Jiro's pick this week is Useful Figure Management Utilities by Michelle Hirsch. One of the reasons I really enjoy programming in MATLAB is the interactive development environment (IDE). The various components allow me to be productive when... read more >>

]]>Jiro's pick this week is Useful Figure Management Utilities by Michelle Hirsch.

One of the reasons I really enjoy programming in MATLAB is the interactive development environment (IDE). The various components allow me to be productive when I'm developing an algorithm or analyzing some data. But what makes the environment even more powerful is the ability to programmatically customize some of the workflows. The 3 useful functions provided by Michelle help with managing your figure windows. The function names are self-explanatory, but here they are.

`figshift`- This is useful when you create a couple of figures and quickly want to be able to click back and forth between the two. Calling this function will shift the current figure window slightly from the previous window, allowing you to easily click between the two.`fillscreen`- As the name suggests, this "maximizes" the figure window to fill the whole screen.`showmethefigs`- This is my favorite. By calling this after you create all the figures, you can cycle through all the figure windows by hitting a key on your keyboard.

While you can use these functions directly from the Command Window, I find them most useful by sprinkling these within my script. This way, my figures will be placed appropriately at the end of the script.

surf(peaks) fillscreen figure plot(rand(10,3)) figure spy(bucky) figshift

**Comments**

This entry was so useful that it inspired Mirko to create "Figure Management Utilities" with additional functionality. Do you have any other favorite utilities that allow you to be more productive with the MATLAB IDE? Tell us about it here or leave a comment for Michelle.

Get
the MATLAB code

Published with MATLAB® R2014a

Idin's pick for this week is Configurable Simulink Model for DC-DC Converters with PWM PI Control by Yi Cao. Dr. Yi Cao has contributed a wealth of useful tools to... read more >>

]]>Idin's pick for this week is Configurable Simulink Model for DC-DC Converters with PWM PI Control by Yi Cao.

Dr. Yi Cao has contributed a wealth of useful tools to the File Exchange (I saw 66 at the time of this writing). This week’s Pick came in handy for me recently as I was trying to investigate and demonstrate the value of Simulink for modeling DC-DC converters .

Power management ICs (PMICs) are critical pieces of most electronic systems, especially battery-operated devices such as mobile phones and tablets. As it was put to me recently, “PMICs are equivalent to the devices that turn the lights on at power-up, and turn them off when powering down.” The PMIC provides required amounts of power to different parts of the system. An important part of a PMIC is typically one or more DC-DC converter to provide regulated voltages to different parts of a system.

In this submission Yi Cao provides a nice example of how the behavior of DC-DC converters can be modeled and simulated in Simulink. These converters fall under three general classes: buck, boost, and buck-boost (buck steps down the input voltage, boost steps it up, and buck-boost inverts the polarity). Yi’s example covers all three classes (using their classic topologies). The core of this submission is a Simulink model that shows how the whole system works.

This model is simulating a full closed-loop system. The converter needs to hold its output voltage constant as the amount of current being drawn varies. The control loop (and the PWM PI controller) work to correct fluctuations in output voltage (usually due to fluctuations in output current). He's done some good work to create one customizable block that can be configured to simulate any desired topology (buck, boost, or buck-boost).

A really nice feature of this submission is the included tutorial (PDF) on deriving the mathematical equations used in the model from circuit diagrams. I highly recommend reading through this document. And if there was any doubt that the derivations were correct, my colleague Dick Benson created a circuit-level model of the same system to check the results.

The results from the circuit simulation were nearly identical to those from Yi’s model. The figure below shows two plots: the output voltage and inductor current. In each plot the result of the circuit simulation is overlaid on top of the output from Yi’s model. The two traces can hardly be distinguished.

If you would like to see some examples of these systems simulated using real circuit elements, download the Mixed-Signal Library from the bottom of this page, and go to the “Switching Power” examples. Note that the examples using circuit elements require SimPowerSystems . As always, your thoughts and comments here are greatly appreciated.

Get
the MATLAB code

Published with MATLAB® R2014a

Sean's pick this week is `mcolon` by Bruno Luong.

Earlier this week there was a question asking how to most efficiently create a vector from multiple colon subscripts, a common enough task. For example:

% Starting index startidx = [1 4 pi] % Stride between each start and ending index stride = [1 -1 pi] % Ending index endidx = [6 0 pi^2]

startidx = 1.0000 4.0000 3.1416 stride = 1.0000 -1.0000 3.1416 endidx = 6.0000 0 9.8696

```
% Desired result
disp(v)
```

1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 4.0000 3.0000 2.0000 1.0000 0 3.1416 6.2832 9.4248This can be accomplished with a simple

To compile the MEX file, you can call the provided

And now the calling syntax:

v = mcolon(startidx,stride,endidx).'; disp(v)

1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 4.0000 3.0000 2.0000 1.0000 0 3.1416 6.2832 9.4248