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. After installing your toolbox, users can either use the factory values or specify their own personal or temporary values.

You can create factory settings for toolboxes using 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 argument as 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 argument as 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 argument. Add read-only settings to prevent toolbox users from changing the settings values.

Place all the factory settings tree creation commands in a function with no inputs. Include the function file with your toolbox code when you package and distribute the toolbox. For example, the function createMyToolboxFactoryTree 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

Create Factory Settings JSON File

To specify the function that creates the factory settings tree for the toolbox, create a JSON file named 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 the root settings group name as mytoolbox, the hidden state as false, and the settings tree creation function as createMyToolboxFactoryTree.

{
"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 verify that the settings are working as expected.

Note

You must add the toolbox folder that contains the settings tree creation function and the toolbox resources folder to the MATLAB® path.

To test the tree, use the matlab.settings.reloadFactoryFile function to load your toolbox factory settings. The settings function gives MATLAB access to the root of the settings tree and your toolbox factory settings tree underneath it.

For example, test the factory settings tree for mytoolbox.

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

Note

  • The matlab.settings.reloadFactoryFile function is meant for debugging purposes only. Do not include the function in shipping toolbox code.

  • You must re-create 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 re-create a to access the updated settings for mytoolbox.

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 that you can use to validate settings.

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 must not be empty.

isempty

mustBeNonsparse(A)

A has no sparse elements.

issparse

mustBeNumeric(A)

A must be numeric.

isnumeric

mustBeNumericOrLogical(A)

A must be 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 argument and specify the function handle. For example, add the setting MyLogicalSetting to the mytoolbox group and specify that its value must be a logical scalar.

addSetting(s.mytoolbox,"MyLogicalSetting",ValidationFcn= ...
    @matlab.settings.mustBeLogicalScalar);

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

s.mytoolbox.MyLogicalSetting.PersonalValue = 10
Error setting 'MyLogicalSetting' in group 'mytoolbox':
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 validates the values of all factory settings within the group that do not specify their own validation functions. The specified function also validates 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.mytoolbox,"mylogicalsettings",ValidationFcn= ...
    @matlab.settings.mustBeLogicalScalar);

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

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

Define Custom Validation Functions

You can create your own validation functions to check factory settings for characteristics that are not covered by the MATLAB validation functions. Validation functions are ordinary MATLAB functions that are designed for 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.mytoolbox,"MyEvenNumberSetting",ValidationFcn=@evenNumberValidationFcn);

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

s.mytoolbox.MyEvenNumberSetting.PersonalValue = 1;
Unable to validate settings data. Error using assert
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.

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.

Caution

Changes to the factory settings tree creation function can affect the saved personal and temporary values of settings for the toolbox. To save a copy of the values of your settings, 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 settings folder. To see the full path for the settings folder, enter 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 Factory Settings Tree

To update the factory settings tree for the latest toolbox version, modify the factory settings tree creation functions.

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.

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 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. Logging changes to the factory settings tree supports backward compatibility for a toolbox with modified settings.

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 log individual changes. For example, the function createMyToolboxSettingsFileUpgraders logs 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 logged 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, log the changes by appending them to the existing instructions or by creating a new upgrader instance.

For example, this code logs 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 Factory Settings JSON File

To specify the function that upgrades the factory settings tree for the toolbox, add the settings tree upgrade function to the factory settings file (settingsInfo.json). For example, in settingsInfo.json for mytoolbox, specify the settings tree upgrade function as createMyToolboxSettingsFileUpgraders.

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

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 upgrade results to verify that the upgrade occurred as intended. Be sure to 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 moved over from the MyFontSize setting as intended. 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.

    upgradeResults = matlab.settings.loadSettingsCompatibilityResults("mytoolbox","Version2")
    upgradeResults = 
      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.

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

  1. Use the settings function to access the root of the settings tree and your toolbox settings. Accessing your toolbox settings triggers the personal settings 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.

    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 allows MATLAB to load the latest upgrade results.. The log is located in the settings folder, in the toolboxname folder.

  • The matlab.settings.reloadFactoryFile and matlab.settings.loadSettingsCompatibilityResults functions are meant for debugging purposes only. Do not include the functions 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 setting 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

| |

Topics