Search code examples
excelmatlabvariable-assignment

How to read a CSV or Excel file of parameter names and values and assign them in MATLAB workspace


I have a Excel file with names of variables and their associated values as columns ash shown below: Parameter table in Excel

I would like to use them in my Simulink model as inputs, therefore I need them to load as variables individually and not as a table or an array.

Please help me in achieving the following results in MATLAB workspace

MATLAB Workspace

Thank you in advance.

Moreover, if the file type needs to be changed to CSV or txt format, I could explore the option.

P.S. I am not using dynamic variable evaluation. These are fixed parameters to be fed to the model.


Solution

  • It would make it slightly easier if the column headings in your Excel table were valid MATLAB names, so that they stay the same when read in as MATLAB table headers. Then you can simply read it in with tbl = readtable( 'mytable.csv' ); you can use this function with xlsx files too, optionally setting the sheet name and range to read.

    Then you could assign all of the variables to your workspace with something like

    % Loop over rows of the table
    for ii = 1:height(tbl)
        % assign variable to base workspace
        assignin( 'base', tbl.ParameterName{ii}, tbl.ParameterDefaultValue(ii) );
    end
    

    It's often easier to manage your data if you have it in the model workspace, or at least a struct rather than lots of "loose" variables, but this should work if you just want something to let you quickly parameterise from your Excel table.