Downsizing a struct with different data type fields
5 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
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!