File Exchange Pick of the Week

Our best user submissions

Leaf Pile!

Sean‘s pick this week is leafpile by Nathaniel Barlow.

As we’re finally starting to see cooler temperatures in New England, the leaves are starting to turn. This fun submission allows MATLAB to make a pile of leaves for you to rake or have your virtual dog play in.

To play with this, I’m going to make a simple one line live script with controls to make it so I can play with the settings. I’ll then hide the code so we can just play with the controls and make leaf piles.


Now let’s do a quick code review of the input parsing step that is used in leafpile. This is the relevant part:

function leafpile(N,type)
%leafpile(leaves,type) makes a random pile of N leaves
% of type 'oak' or 'maple'.  N. Barlow 9/28/19
%leafpile(N) makes a mixed pile of N leves.
%leafpile makes a pile of 70 mixed leaves.
%The mathematical functions describing the leaf shapes were created by Hamid Naderi
%Yeganeh and given at https://blogs.scientificamerican.com/guest-blog/how-to-draw-with-math/

if nargin==0,N=70; type='mixed'; end;
if nargin==1, type='mixed'; end;

Using the new arguments construct that Jiro wrote about last week (my personal favorite R2019b feature) this could be rewritten with the following which would also validate the inputs:

function leafpile(N,type)


arguments
    N(1,1) double {mustBeInteger, mustBePositive} = 70;
    type {mustBeMember(type, {'mixed', 'maple', 'oak'})} = 'mixed';
end

Now what makes arguments better? Well, in theory the parsing should be easier to understand and read like an English sentence. But there’s more – Check out the Easter Egg at 26s in the video above. Autocomplete knew the options because they were constrained by mustBeMember. Pretty cool, eh?!

Comments

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

Published with MATLAB® R2019b

|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.