File Exchange Pick of the Week

Our best user submissions

The Matrix Lab Has You

Sean's pick this week is The Matrix lab has you by Mathworlds.

I discovered this after reading Brett's post a couple weeks ago. It's a fun submission that you guys can run yourself - I won't spoil it. This submission does rely on some undocumented capabilities that will break in the future (some already have). But there will be replacements for those, some already available.

The thing that caught my eye about this submission was the word of warning on the FEX page: NB : Running this programs clears your Matlab console and may also change some of your Matlab preferences (font and background colors) if interrupted while running.

The fact that it doesn't reset if interrupted tells me there is improvement for how this function should tear itself down. Right now it:

  1. Gets the original settings values
  2. Sets new settings values
  3. Runs the demo
  4. Sets the settings back to the original value

So if you break with ctrl+c or an error occurs, [4] never gets to run. There's a better way to do this using onCleanup objects. These reliably fire when the object is cleared regardless of if there is an error!

I'll demonstrate by changing the command window error color for this MATLAB session using the new documented settings API.

s = settings;
s.matlab.colors.commandwindow.ErrorColor.TemporaryValue = [0 0 255] % blue errors
colorresetter = onCleanup(@()s.matlab.colors.commandwindow.ErrorColor.clearTemporaryValue())
s = 
  SettingsGroup with properties:
                slhistory: [1×1 SettingsGroup]
                 Simulink: [1×1 SettingsGroup]
                   matlab: [1×1 SettingsGroup]
colorresetter = 
  onCleanup with properties:

    task: @()s.matlab.colors.commandwindow.ErrorColor.clearTemporaryValue()

Now when the colorresetter variable is cleared, it will automatically clear the value that I'd set. In a function, this would happen implicitly at the end. So the fact that this error occurs does not mean I'm permanently stuck or need to manually adjust the setting.

error('smurf:error', 'This error message is blue')
Error using mainMatrixLabHasYou (line 52)
This error message is blue

I use onCleanup objects all of the time. Some frequent things I'll use them for:

  • Changing a setting
  • fclose(fid)
  • Changing directories to somewhere else
  • Deleting a temporary file or folder I created

In the scope of unit testing, you should use the testCase.addTeardown method which will also reliably fire a task but do it in the right phase of the test execution.


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

Published with MATLAB® R2020b

  • print


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