Azzera filtri
Azzera filtri

Data type conversion in struct fields

4 visualizzazioni (ultimi 30 giorni)
Ubaldo
Ubaldo il 25 Lug 2016
Commentato: Guillaume il 25 Lug 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 Commenti
Adam
Adam il 25 Lug 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 il 25 Lug 2016
@Adam, find_system is a simulink function. It returns a cell array of strings.

Accedi per commentare.

Risposte (2)

Azzi Abdelmalek
Azzi Abdelmalek il 25 Lug 2016
Modificato: Azzi Abdelmalek il 25 Lug 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 il 25 Lug 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.

Categorie

Scopri di più su Programmatic Model Editing in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by