필터 지우기
필터 지우기

Downsizing a struct with different data type fields

조회 수: 1 (최근 30일)
Matheus  Pacifici
Matheus Pacifici 2019년 9월 13일
댓글: Matheus Pacifici 2019년 9월 25일
I have a 66x1 struct and want to transform into a 1x1. The struct contains logical, numerical, datetime and string fields. I used
for fieldCtr = 1:length(myfields)
if isnumeric(getfield(oldstruct,myfields{fieldCtr}))
eval(['newStruct.' myfields{fieldCtr} ' = [oldstruct.' myfields{fieldCtr} '];'])
else
isstring(getfield(oldstruct,myfields{fieldCtr}))
evalc(['newStruct.' myfields{fieldCtr} ' = [oldstruct.' myfields{fieldCtr} '];'])
end
end
It works for every data type. except that the strings are now concatenated and all the fields that cointain strings became one huge string.
How can I avoid that? Or is there any smarter way to downsize the entire struct?
  댓글 수: 2
Stephen23
Stephen23 2019년 9월 13일
편집: Stephen23 2019년 9월 13일
Using eval to access fields of a structure has been outdated for fifteen years:
You should use dynamic fields:
"Or is there any smarter way to downsize the entire struct?"
struct2cell, reshape and/or permute, cell2struct
Walter Roberson
Walter Roberson 2019년 9월 13일
The only difference between eval() and evalc() is that evalc() "captures" any text that results from executing the command (such as by a disp() or fprintf()) and makes that text available. There is no difference in how eval() or evalc() treat numeric vs non-numeric fields.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2019년 9월 13일
nfield = length(myfields);
newStruct = cell2stuct(cell(nfield,1), myfields);
for fieldCtr = 1 : nfield
thisfield = myfields{fieldCtr};
sample = oldstruct(1).(thisfield);
if isrow(sample)
newStruct.(thisfield) = vertcat(oldstruct.(thisfield));
elseif iscolumn(sample)
newStruct.(thisfield) = horzcat(oldstruct.(thisfield));
else
nd = ndims(sample);
newStruct.(thisfield) = cat(nd+1, oldstruct.(thisfield));
end
end
This code tries to be intelligent about how to arrange the results. It turns rows into 2D arrays by vertical concatenation; it turns columns into 2D arrays by horizontal concatenation; it turns other arrays into one higher dimension by concatenating one dimension higher than it already is (so for example, two 32 x 64 arrays would not turn into 64 x 64 or 32 x 128, and would instead turn into 32 x 64 x 2)
You might want to make an exception for character vectors: instead of creating a character array, you might want to create a cell array of character vectors, so as to allow for the possibility that the character vectors are different lengths.
  댓글 수: 1
Matheus  Pacifici
Matheus Pacifici 2019년 9월 25일
Thank you Roberson,
It works perfectly for every struct I tried.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by