Main Content

Create Factory Settings for Toolboxes

If you create a toolbox that works with MathWorks® products, you can add settings to the toolbox that enable users 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 using the matlab.settings.FactoryGroup.createToolboxGroup function. 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 so that the group is visible in the factory settings tree, either when displayed in the Command Window or as part of tab completion.

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

Once the toolbox root factory group is created, create the factory settings tree by adding factory settings and factory settings groups to the root. 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 to store the font settings for your toolbox.

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 settings values.

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 and adds the factory group font and two factory settings, MyFontSize and MyFontColor, to the tree.

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

    toolboxFontGroup = addGroup(myToolboxFactoryTree,'font','Hidden',false)
    addSetting(toolboxFontGroup,'MyFontSize','FactoryValue',11,'Hidden',false)    
    addSetting(toolboxFontGroup,'MyFontColor','FactoryValue','Black', ...
        'Hidden',false);
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 validation functions.

Name

Meaning

Functions Called on Inputs

matlab.settings.mustBeStringScalar(A)

A must be a string scalar.

isStringScalar

matlab.settings.mustBeLogicalScalar(A)

A must be a logical scalar.

islogical, isscalar

matlab.settings.mustBeNumericScalar(A)

A must be a numeric scalar.

isnumeric, isscalar

matlab.settings.mustBeIntegerScalar(A)

A must be an integer scalar.

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 factory settings for properties that are not covered by the MATLAB validation functions. Validation functions are ordinary MATLAB functions that are designed for the purpose of validating the values of settings. 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 an even number.

function evenNumberValidationFcn(x)
    errorMsg = 'Value must be an even number.';
    iseven = isnumeric(x) && mod(x, 2) == 0;
    assert(iseven,errorMsg);
end

Add this validation function to a new setting.

addSetting(s.mysettings,'MyEvenNumberSetting','ValidationFcn',@evenNumberValidationFcn);

Set the value of MyEvenNumberSetting to an odd number. As expected, MATLAB throws an error.

s.mysettings.MyEvenNumberSetting.PersonalValue = 1;
Unable to validate settings data. Error using evenNumberValidationFcn (line 4)
Value must be an even number.

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 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.

{
"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"
}

Note

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

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 to ensure the settings are working as expected.

To test the tree, 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. This gives MATLAB access to 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:

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>
  InstallationValue: <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

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, toolboxname.mlsettings, is located in your preferences folder. 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.

Modify 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 represent 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');
    move(upgraders,"mytoolbox.font.MyFontSize","mytoolbox.font.FontSize");
    move(upgraders,"mytoolbox.font.MyFontColor","mytoolbox.font.FontColor"); 

end

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');
    move(upgraders,"mytoolbox.font.MyFontSize","mytoolbox.font.FontSize");
    move(upgraders,"mytoolbox.font.MyFontColor","mytoolbox.font.FontColor"); 

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

Modify the Factory Settings JSON 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.

To ensure the upgrade occurs correctly, examine the upgrade results before distributing the toolbox. 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
     InstallationValue: <no value>
          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.

Listen For Changes to Toolbox Settings

If you add settings to your toolbox for toolbox users to modify, you can create settings listeners to detect when a setting value changes so that your toolbox can react to the change. To create a setting listener, use the addlistener function.

For example, create a settings listener for the mytoolbox.font.FontSize setting.

s = settings;
settingListener = addlistener(s.mytoolbox.font,'FontSize','PostSet', ...
    @(src,evnt)disp('Font size changed'));

Set the value of the FontSize setting to 12. Setting the value triggers the PostSet event on the setting.

s.mytoolbox.font.FontSize.PersonalValue = 12;
Font size changed

See Also

| |

Related Topics