Create a set of parameters from a excel file

5 views (last 30 days)
Ismael
Ismael on 19 Mar 2025
Answered: Aastha on 24 Mar 2025
I want to programmaticaly create a code that reas in an excel file and creates a set of parameters (constants) with their corresponding values in matlab WORKSPACE or "MODEL DATA"
The excel file looks like this:
Param Case1 Case2
speed 10 12
length 14 25
I have already a Simulink model that expects the corresponding value of "speed" and "length". In this case, the script will be part of the initialisation of the model so that those parameters will not be void for the simulation.
I dont't mind if they will be in the matlab "workspace" or in the "MODEL DATA" of my simulaink model.
any idea?
Thanks

Answers (1)

Aastha
Aastha on 24 Mar 2025
I understand that you want to create MATLAB workspace variables with names corresponding to the rows in your Excel file and values from the columns. You may refer to the steps mentioned below to do so:
1) Create dummy data and save it as an Excel file with name “dummy_parameters.xlsx”. The MATLAB code below illustrates this:
% As an example I created a table with dummy data
paramNames = {'speed'; 'length'};
case1Values = [10; 14];
case2Values = [12; 25];
% Combine into a table
dummyTable = table(paramNames, case1Values, case2Values, ...
'VariableNames', {'Param', 'Case1', 'Case2'});
% Write the table to an Excel file
excelFileName = 'dummy_parameters.xlsx';
writetable(dummyTable, excelFileName);
2) Read the dummy Excel file using the “readtable” function in MATLAB. Kindly refer to the MATLAB code below to do this:
paramTable = readtable(excelFileName);
Refer to the MathWorks documentation for any further information on the “readtable” function.
3) Select the column to assign values to the created variables. As an example, let the name of the column be “Case1”.
selectedCase = 'Case1';
4) Use the “assignin” function in MATLAB to specify the parameter name and value. This will create a variable in the MATLAB workspace with the specified name and value.
% Loop through each parameter and assign it to the workspace
for i = 1:height(paramTable)
paramName = paramTable.Param{i}; % Get the parameter name
paramValue = paramTable.(selectedCase)(i); % Get the parameter value for the selected case
% Assign the parameter to the base workspace
assignin('base', paramName, paramValue);
end
You may refer to the MathWorks documentation of “assignin” function for more information on it.
I hope this helps!

Categories

Find more on Data Import from MATLAB in Help Center and File Exchange

Products


Release

R2024a

Community Treasure Hunt

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

Start Hunting!