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!