Downsizing a struct with different data type fields
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!