Data type conversion in struct fields

조회 수: 6 (최근 30일)
Ubaldo
Ubaldo 2016년 7월 25일
댓글: Guillaume 2016년 7월 25일
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에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by