Data type conversion in struct fields

3 views (last 30 days)
Ubaldo on 25 Jul 2016
Commented: Guillaume on 25 Jul 2016
Hi all,
I am running the following:
Foo = 'MyModel/Foo';
blks = find_system(Foo,'BlockType','Constant');
TEMP_PAR = {''};
jj = 1;
for ii=1:length(blks);
Blk_name = get_param(blks(ii),'Name');
if ~strncmp(Blk_name,'Constant',8) && isempty(find(strcmp(Blk_name,TEMP_PAR),1))
TEMP_PAR(jj,1) = Blk_name;
TEMP_PAR(jj,2) = get_param(blks(ii),'Value');
jj = jj+1;
% create the DST struct
PAR.MySet = cell2struct(PAR_VALUES,PAR_NAMES,1);
But what I get in my struct is a set of parameters like
obs_c1: 'TempCoef(5)'
obs_c2: 'TempCoef(6)'
T0K: '273.15'
T0K1: '298'
Cp0_Cool: '3600'
Where the numerical array TempCoef is defined in the Workspace. What I would like is have the value of the fields as numbers, for example like this:
obs_c1: 27.2
obs_c2: -5.9
T0K: 273.15
T0K1: 298
Cp0_Cool: 3600
I tried str2double but it messes up the variables defined in the workspace. Any hint? Many thanks.
Guillaume on 25 Jul 2016
@Adam, find_system is a simulink function. It returns a cell array of strings.

Sign in to comment.

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 25 Jul 2016
Edited: Azzi Abdelmalek on 25 Jul 2016
This is not the best way to do but it works.
v.obs_c1= 'TempCoef(5)'
v.obs_c2= 'TempCoef(6)'
v.T0K= '273.15'
v.T0K1= '298'
v.Cp0_Cool= '3600'
%-----------The code-------------------
for k=1:numel(name)
v.(name{k})=evalin('base', v.(name{k}))
Maybe you can avoid this situation by modifying your initial code

Guillaume on 25 Jul 2016
I know nothing about simulink. Ideally, there would be a similar function to get_param that return the evaluated value of the parameter. Failing that, this is probably one of the rare cases where using eval makes sense:
TEMP_PAR(jj,2) = eval(get_param(blks(ii),'Value'))
Be aware that eval will execute whatever instruction is contained in the value of your parameter. So if one the values happens to be the string 'rm('C:\', 's')', it will happily reformat your hard disk.


Find more on Programmatic Model Editing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!