Create Factory Settings for Toolboxes

If you create a toolbox that works with MathWorks® products, you can add settings to the toolbox that toolbox users can use to customize the appearance and behavior of the toolbox after installation. For example, you can add a setting that allows a user to change the font size in your toolbox.

To add settings that include factory values that ship with the toolbox, create factory settings. After installing your toolbox, users can then either use the factory values, or specify their own personal or temporary values.

Creating factory settings for toolboxes involves these steps:

  1. Create the factory settings tree.

  2. Create the factory settings JSON file.

  3. Test the factory settings tree.

Create Factory Settings Tree

The first step to creating factory settings for a toolbox is to create the factory settings tree. Use the matlab.settings.FactoryGroup.createToolboxGroup function to create the root factory settings group for a toolbox. For example, create the root factory group for the toolbox mytoolbox. By default, factory groups are hidden, which means that they do not display in the parent settings group. Specify the 'Hidden' name-value pair with a value of false to ensure that the group is visible in the factory settings tree.

myToolboxFactoryTree = matlab.settings.FactoryGroup.createToolboxGroup('mytoolbox','Hidden',false);

Once the toolbox root factory group is created, add factory settings and factory settings groups to the root to create the factory settings tree.

To add a new factory settings group, use the addGroup function. Specify the 'Hidden' name-value pair with a value of false to create a visible factory group. For example, add the font factory group as a visible group.

toolboxFontGroup = addGroup(myToolboxFactoryTree,'font','Hidden',false)
toolboxFontGroup = 
  FactoryGroup with properties:

             Name: "font"
    ValidationFcn: []
          Hidden: 0

To add a new factory setting, use the addSetting function. For example, add FontSize as a visible factory setting in the font factory group. Specify a factory value for the setting. This value ships with the toolbox.

addSetting(toolboxFontGroup,'FontSize','FactoryValue',11,'Hidden',false)
ans = 

  FactorySetting with properties:

               Name: "FontSize"
       FactoryValue: 11
    FactoryValueFcn: []
      ValidationFcn: []
             Hidden: 0
           ReadOnly: 0

You also can add read-only settings using the 'ReadOnly' name-value pair argument. Add read-only settings to prevent toolbox users from changing the value of the settings by specifying a temporary or personal value for the setting.

Place all of the factory settings tree creation commands in a function with no inputs. Include the function with your toolbox code when you package and distribute the toolbox. For example, the function createMyToolboxFactoryTree.mlx creates the factory settings tree for the toolbox mytoolbox.

function myToolboxFactoryTree = createMyToolboxFactoryTree()
    myToolboxFactoryTree = matlab.settings.FactoryGroup.createToolboxGroup('mytoolbox', ...
        'Hidden',false);

    toolboxFontGroup = addGroup(myToolboxFactoryTree,'font','Hidden',false)
    addSetting(toolboxFontGroup,'MyFontSize','FactoryValue',11,'Hidden',false, ...
        'ValidationFcn',@matlab.settings.mustBeNumericScalar)    
    addSetting(toolboxFontGroup,'MyFontColor','FactoryValue','Black', ...
        'Hidden',false,'ValidationFcn',@matlab.settings.mustBeStringScalar);
end

Validate Settings Using Functions

You can impose specific restrictions on settings values by specifying a validation function for a setting or group. A validation function accepts a potential setting value as an argument, and throws an error if the value does not meet a specific requirement.

MATLAB® defines several useful validation functions.

Name

Meaning

Functions Called on Inputs

matlab.settings.mustBeStringScalar(A)

A is a string array with one element.

isStringScalar

matlab.settings.mustBeLogicalScalar(A)

A is logical with one element.

islogical, isscalar

matlab.settings.mustBeNumericScalar(A)

A is numeric with one element.

isnumeric, isscalar

matlab.settings.mustBeIntegerScalar(A)

A is an integer with one element.

isinteger, isscalar

mustBePositive(A)

A > 0

gt, isreal, isnumeric, islogical

mustBeNonpositive(A)

A <= 0

ge, isreal, isnumeric, islogical

mustBeFinite(A)

A has no NaN and no Inf elements.

isfinite

mustBeNonNan(A)

A has no NaN elements.

isnan

mustBeNonnegative(A)

A >= 0

ge, isreal, isnumeric, islogical

mustBeNegative(A)

A < 0

lt, isreal, isnumeric, islogical

mustBeNonzero(A)

A ~= 0

eq, isnumeric, islogical

mustBeNonempty(A)

A is not empty.

isempty

mustBeNonsparse(A)

A has no sparse elements.

issparse

mustBeNumeric(A)

A is numeric.

isnumeric

mustBeNumericOrLogical(A)

A is numeric or logical.

isnumeric, islogical

mustBeReal(A)

A has no imaginary part.

isreal

mustBeInteger(A)

A == floor(A)

isreal, isfinite, floor, isnumeric, islogical

To specify a validation function when creating a factory setting, use the 'ValidationFcn' name-value pair argument and specify the function handle. For example, add the setting MyLogicalSetting to the myfactorysettings group and specify that its value must be a logical scalar.

addSetting(s.myfactorysettings,'MyLogicalSetting','ValidationFcn', ...
    @matlab.settings.mustBeLogicalScalar);

Try setting the value of MyLogicalSetting to a nonlogical value. As expected, MATLAB throws an error.

s.myfactorysettings.MyLogicalSetting.PersonalValue = 10
Error setting "MyLogicalSetting" in group "myfactorysettings": Value must be logical or convertible to logical.

You also can specify a validation function for an entire factory settings group. When specified, the function is used to validate the values of all factory settings within the group that do not specify their own validation functions. This includes settings in subgroups, as long as the subgroup or settings do not specify their own validation functions. For example, create the settings group mylogicalsettings and specify the validation function matlab.settings.mustBeLogicalScalar.

addGroup(s.myfactorysettings,'mylogicalsettings','ValidationFcn', ...
    @matlab.settings.mustBeLogicalScalar);

Create the setting MyLogicalSetting within the mylogicalsettings group and try setting the value of the setting to a nonlogical value. As expected, MATLAB throws an error.

addSetting(s.myfactorysettings.mylogicalsettings,'MyLogicalSetting')
s.myfactorysettings.mylogicalsettings.PersonalValue = 10;
Error setting 'MyLogicalSetting' in group 'mysettings': Value must be logical or convertible to logical.

Define Custom Validation Functions

You also can create your own validation functions to check for factory settings properties that are not covered by the MATLAB validation functions. Validation functions are ordinary MATLAB functions that are designed for the purpose of validating settings values. They must satisfy these conditions:

  • Accept the potential setting value as an input argument.

  • Have no output arguments.

  • Throw an error if the validation fails.

Place validation functions on the MATLAB path to make them available.

For example, create a function to validate whether the value of a setting is numeric.

function numericValidationFcn(x)
    errorMsg = 'Value must be numeric.'; 
    assert(isnumeric(x),errorMsg);
end

Add this validation function to a new setting.

addSetting(s.mysettings,'MyNumericSetting','ValidationFcn',@numericValidationFcn);

Set the value of MyNumericSetting to a nonnumeric value. As expected, MATLAB throws an error.

s.mysettings.MyNumericSetting.PersonalValue = 'Hello';
Unable to validate settings data. Error using myvalidationFcn (line 3)
Value must be numeric.

You also can create custom validation functions to make use of MATLAB validation functions that require multiple inputs, such as mustBeGreaterThan, mustBeLessThan, mustBeGreaterThanOrEqual, mustBeLessThanOrEqual, and mustBeMember. For example, this function validates that the value of a setting is one of four colors.

function colorValidationFcn(val) 
    mustBeMember(val, ['Black' 'Blue' 'Yellow' 'Green']); 
end

For more information about adding a validation function to a factory setting or factory settings group, see addSetting and addGroup.

Create Factory Settings JSON File

In order for MATLAB to know what function to use to create the factory settings tree, create a JSON-formatted file called settingsInfo.json. Include the file in the toolbox resources folder when you package and distribute the toolbox.

settingsInfo.json must follow this template. The ToolboxGroupName and CreateTreeFcn elements are required.

Note

The values for ToolboxGroupName and Hidden must match the toolbox root factory group name and hidden state.

{
"ToolboxGroupName" : "[toolbox root factory group name]",
"Hidden" : "[hidden state of toolbox root factory group]",
"CreateTreeFcn" : "[toolbox factory tree creation function]", 
"CreateUpgradersFcn" : "[toolbox factory tree upgrade function]"
}

For example, create the settingsInfo.json file for mytoolbox. Specify mytoolbox as the root settings group name, false as the hidden state, and createMyToolboxFactoryTree as the settings tree creation function.

{
"ToolboxGroupName" : "mytoolbox",
"Hidden" : "false",
"CreateTreeFcn" : "createMyToolboxFactoryTree"
}

Test Factory Settings Tree

After creating the settings tree creation function and the settingsInfo.json file for your toolbox, you can test the settings tree before packaging and distributing the toolbox. Testing is useful for ensuring that the structure of the tree and the behavior of the settings are working as expected.

To test the tree, first, add the toolbox folder that contains the settings tree creation function and the toolbox resources folder to the MATLAB path. Then, use the matlab.settings.reloadFactoryFile function to load your toolbox factory settings and the settings function to access the root of the settings tree and your toolbox factory settings tree underneath it.

Note

To avoid unexpected results, you must add the toolbox folder that contains the settings tree creation function and the toolbox resources folder to the MATLAB path.

For example, to test the factory settings tree for mytoolbox, you can run this code.

matlab.settings.reloadFactoryFile('mytoolbox');
s = settings;
s.mytoolbox.font.MyFontSize
ans = 
  Setting 'mytoolbox.font.MyFontSize' with properties:
       ActiveValue: 11
    TemporaryValue: <no value>
     PersonalValue: <no value>
      FactoryValue: 11

Note

  • The matlab.settings.reloadFactoryFile function is meant for debugging purposes only and should not be included in shipping toolbox code.

  • You must recreate any variables that reference the specified toolbox after calling matlab.settings.reloadFactoryFile. For example, if you create the variable a = s.mytoolbox and then call matlab.settings.reloadFactoryFile, you must recreate a to access the updated settings for mytoolbox.

Ensure Backward Compatibility Across Toolbox Versions

If you want to create a new version of your toolbox that includes modifications to the factory settings tree, you can take steps to ensure that any personal settings configured in a previously installed version of the toolbox are properly moved to the upgraded factory settings tree.

To ensure backward compatibility when making modifications to the factory settings tree, follow these steps:

  1. Modify the factory settings tree.

  2. Log changes to the tree.

  3. Modify the factory settings JSON file.

  4. Examine personal settings tree upgrade results.

Modifications that can cause backward incompatibility issues include renaming, moving, and removing toolbox factory settings or settings groups. If you are adding new settings to the factory settings tree, then you do not need to follow these steps.

Warning

Changes to the factory settings tree creation function can affect the saved personal and temporary values of settings for the toolbox in question. To avoid data loss, back up your toolbox settings file before making any changes or before upgrading your toolbox. The toolbox settings file is located in your preferences folder, and has the name toolboxname.mlsettings. To see the full path for the preferences folder, type prefdir in the MATLAB Command Window.

If you experience unexpected changes to a toolbox settings tree after an upgrade, you can restore the tree by replacing the toolbox settings file with the backup that you created.

Update the Factory Settings Tree

The factory settings tree creation function creates the settings tree for the latest toolbox version. To update the factory settings tree for the latest toolbox version, modify the factory settings tree creation commands.

Note

The commands in the factory settings tree creation function represents the latest toolbox version settings tree.

For example, suppose that in version 2 of mytoolbox, you want to rename the settings MyFontSize and MyFontColor to FontSize and FontColor. Change the settings names in createMyToolboxFactoryTree.mlx.

function myToolboxFactoryTree = createMyToolboxFactoryTree()
    myToolboxFactoryTree = matlab.settings.FactoryGroup.createToolboxGroup('mytoolbox', ...
        'Hidden',false);

    toolboxFontGroup = addGroup(myToolboxFactoryTree,'font','Hidden',false)
    addSetting(toolboxFontGroup,'FontSize','FactoryValue',11,'Hidden',false, ...
        'ValidationFcn',@matlab.settings.mustBeNumericScalar)    
    addSetting(toolboxFontGroup,'FontColor','FactoryValue','Black', ...
        'Hidden',false,'ValidationFcn',@matlab.settings.mustBeStringScalar);
end

Log Changes to the Tree

Create a function with no inputs to store the instructions for upgrading the personal settings from a previous version of the toolbox. Include the file with your toolbox code when you package and distribute the toolbox. Recording changes to the factory settings tree ensures that toolbox users upgrading to a new version do not have backward incompatibility issues with their existing toolbox settings. Modifications that can cause backward incompatibility issues include renaming, moving, and removing toolbox factory settings or settings group. You do not need to record the addition of new settings to the factory settings tree.

In the function, add a settings file upgrader object for each version of the toolbox that contains changes to the factory settings tree. Use the move and remove functions to record individual changes. For example, the function createMyToolboxSettingsFileUpgraders.mlx records the changes to MyFontSize and MyFontColor for version 2 of mytoolbox.

function upgraders = createMyToolboxSettingsFileUpgraders()
    upgraders = matlab.settings.SettingsFileUpgrader('Version2');
    upgraders.move("mytoolbox.font.MyFontSize","mytoolbox.font.FontSize");
    upgraders.move("mytoolbox.font.MyFontColor","mytoolbox.font.FontColor"); 

end

Note

Do not modify recorded upgrade instructions in the settings tree upgrade function after packaging and distributing the toolbox to your users. Modifying instructions can have unexpected results. If you make additional changes to the settings tree, record the changes by appending them to the existing instructions, or by creating a new upgrader instance.

For example, this code records changes for version 2 and version 3 of mytoolbox.

function upgraders = createMyToolboxSettingsFileUpgraders()
    upgraders = matlab.settings.SettingsFileUpgrader('Version2');
    upgraders.move("mytoolbox.font.MyFontSize","mytoolbox.font.FontSize");
    upgraders.move("mytoolbox.font.MyFontColor","mytoolbox.font.FontColor"); 

    upgraders(2) = matlab.settings.SettingsFileUpgrader('Version3');
    upgraders(2).remove("mytoolbox.font.FontName"); 
end

Modify Factory Settings File

In order for MATLAB to know what function to use to upgrade the toolbox factory settings tree, specify the settings tree upgrade function in the factory settings file (settingsInfo.json). For example, in settingsInfo.json for mytoolbox, specify createMyToolboxSettingsFileUpgrader as the settings tree upgrade function.

{
"ToolboxGroupName" : "mytoolbox",
"Hidden" : "false",
"CreateTreeFcn" : "createMyToolboxFactoryTree",
"CreateUpgradersFcn" : "createMyToolboxSettingsFileUpgraders"
}

Include the files createMyToolboxFactoryTree.mlx, createMyToolboxSettingsFileUpgraders.mlx, and settingsInfo.json when you package and distribute mytoolbox. Place the settingsInfo.json in the toolbox resources folder.

Note

You must restart MATLAB after changing the settingsInfo.json file.

Examine Personal Settings Tree Upgrade Results

After upgrading the personal settings of a toolbox, you can examine the results to ensure that the upgrade occurred correctly. To examine the upgrade results, use the matlab.settings.loadSettingsCompatibilityResults function.

Examining the upgrade results before distributing a toolbox is useful to ensure that the upgrade will occur correctly after the toolbox has been distributed. For example, examine the upgrade results for version 2 of mytoolbox before distributing the toolbox.

  1. Reload the factory settings tree for mytoolbox.

    matlab.settings.reloadFactoryFile('mytoolbox');
  2. Use the settings function to access the root of the settings tree and verify that the personal value for the FontSize setting was correctly moved over from the MyFontSize setting. Accessing your toolbox settings triggers the personal settings upgrade process.

    s = settings;
    s.mytoolbox.font.FontSize
    ans = 
      Setting 'mytoolbox.font.FontSize' with properties:
           ActiveValue: 15
        TemporaryValue: <no value>
         PersonalValue: 15
          FactoryValue: 11
  3. Run the matlab.settings.loadSettingsCompatibilityResults function to get the upgrade results for version 2 of mytoolbox. Verify that there are no prevalidation exceptions.

    matlab.settings.loadSettingsCompatibilityResults('mytoolbox','Version2')
    ans = 
      ReleaseCompatibilityResults with properties:
                   VersionLabel: "Version2"
        PreValidationExceptions: [0×0 matlab.settings.ReleaseCompatibilityException]
                        Results: [1×1 matlab.settings.VersionResults]
  4. Access the Results property to determine the number of upgrade operations performed.

    upgradeResults.Results
    ans = 
      VersionResults with properties:
          VersionLabel: "Version2"
        VersionChanges: [1×2 matlab.settings.OperationResult]
  5. Check the status of each upgrade operation to ensure that they were performed successfully.

    upgradeResults.Results.VersionChanges.Status
    ans = 
        "Succeeded"
    
    ans = 
        "Succeeded"
    

You also can examine upgrade results after you have installed a new version of a toolbox. This approach is useful, for example, if you are helping a toolbox user troubleshoot their toolbox settings after an upgrade.

For example, suppose that you have version 1 of mytoolbox installed and have set personal values for several settings. After installing version 2 of mytoolbox, examine the upgrade results to ensure that your personal settings moved over correctly.

  1. Use the settings function to access the root of the settings tree and your toolbox settings. Accessing your toolbox settings triggers the personal setting upgrade process.

    s = settings;
    s.mytoolbox
    ans = 
      SettingsGroup 'mytoolbox' with properties:
        font: [1×1 SettingsGroup]

  2. Run the matlab.settings.loadSettingsCompatibilityResults function to get the upgrade results. Check the status of each upgrade operation performed to ensure that they were performed successfully.

    upgradeResults = matlab.settings.loadSettingsCompatibilityResults('mytoolbox','Version2');
    upgradeResults.Results.VersionChanges.Status
    ans = 
        "Succeeded"
    
    ans = 
        "Succeeded"
    

Note

  • After running the matlab.settings.reloadFactoryFile and matlab.settings.loadSettingsCompatibilityResults functions, delete the log of results before running the functions again. Deleting the log ensures the correct upgrade results are always loaded. The log is located in the preferences folder, in the toolboxname folder.

  • The matlab.settings.reloadFactoryFile and matlab.settings.loadSettingsCompatibilityResults functions are meant for debugging purposes only and should not be included in shipping toolbox code.

See Also

| |

Related Topics