Load parameters from .MAT to simulink block

2 次查看(过去 30 天)
Hi.
Is there a way to have a button of similar in the parameters window of a custom block that allow the user to upload a .MAT and use the data in the file as the values of the block's parameters?
I know i might be able to do this one time writing it in the initialization script but i want to be able to change the file at any time without deleting the block.
Thank you!

回答(1 个)

Rajanya
Rajanya 2025-2-7
You can add a 'push button' to the mask of the custom block which will help select files, as and when needed, without having to delete the block. The button should have a callback which will take the file selected by the user using 'uigetfile' and load the data of the file in MATLAB base workspace. The data from the .MAT file would be loaded as a 'struct', containing all the data fields and their corresponding values.
Consequently, any parameter of any block in the model, including the custom block itself, can be configured to reference a specific field from the loaded data. This enables the parameter's value to dynamically update whenever new files are loaded, as long as the files consistently contain the same field(s) which has been set as the parameter name(s) of the block.
Below is an example model where the 'Subsystem' block has been used as a custom block with a 'button' and an 'edit field' (with name 'B') as parameters.
The following callback was added to the button -
[file, path] = uigetfile('*.mat', 'Select a MAT-file'); %select the desired file
data = load(strcat(path,file)); %concatenate path and file to get full actual path and load file
assignin('base', 'loadedData', data); %post data to base workspace with name 'loadedData'
The parameter 'B' was then set to 'loadedData.B'. (requirement: the file should have a data field 'B' present in it)
set_param(gcb,'B','loadedData.B');
Once a .MAT file is selected (which, in this example, contains a value of 102 for 'B'), this value is instantly applied as the parameter value for 'B'. As different files are chosen, the parameter value dynamically updates to reflect the 'B' values contained in each new file.
To learn more about the functionality of 'assignin' and 'uigetfile', you can refer to their respective documentation pages by executing the following commands from the MATLAB Command Window:
doc assignin
doc uigetfile
Hope this answers your question. Thanks!

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by