Data type conversion in struct fields

6 visualizaciones (últimos 30 días)
Ubaldo
Ubaldo el 25 de Jul. de 2016
Comentada: Guillaume el 25 de Jul. de 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;
end
end
% create the DST struct
PAR_NAMES = TEMP_PAR(:,1);
PAR_VALUES = TEMP_PAR(:,2);
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.
  2 comentarios
Adam
Adam el 25 de Jul. de 2016
Without knowing anything about what find_system returns it is very hard to follow the flow of code that leads to you having these values for your struct in the first place.
str2double should work fine for the last 3 fields, though obviously not the first 2.
Guillaume
Guillaume el 25 de Jul. de 2016
@Adam, find_system is a simulink function. It returns a cell array of strings.

Iniciar sesión para comentar.

Respuestas (2)

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

Guillaume
Guillaume el 25 de Jul. de 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.

Categorías

Más información sobre Programmatic Model Editing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by