Data type conversion in struct fields

4 次查看(过去 30 天)
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 个评论
Adam
Adam 2016-7-25
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 2016-7-25
@Adam, find_system is a simulink function. It returns a cell array of strings.

请先登录,再进行评论。

回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-7-25
编辑:Azzi Abdelmalek 2016-7-25
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 2016-7-25
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.

类别

Help CenterFile Exchange 中查找有关 Programmatic Model Editing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by