How to work with function inputs which are structures with different fields
1 次查看(过去 30 天)
显示 更早的评论
I have a function. The inputs are multiple structures which have some of the same fields but also some different fields. I may pass in 1 structure or 10, or even an empty structure, struct([]). Inside the function, I would like to walk through varargin and create a structure array containing all the different structures. How can I do this?
I tried the following but get the error 'Subscripted assignment between dissimilar structures'. Is there a better way to handle these inputs?
iCount = 0; % Index to non-empty structures
for iArg = 1:length(varargin)
if ~isempty(varargin{iArg}) % Ignore empty structures if they are passed in
iCount = iCount + 1;
SIn(iCount) = varargin{iArg}; % Build the structure array
end
end
0 个评论
采纳的回答
Guillaume
2019-5-16
By definition, the fields of each structure element of a structure array are all the same. The field names are a property of the array, not of the individual elements. So, it is impossible to store scalar structures with different fields in a structure array. At least, not without adding the missing fields to all the structures (which can be done efficiently if needed).
Instead you can store the dissimilar structures into a cell array. Cell arrays are designed to store heterogeneous data. But note that you already have these structures stored in a cell array: varargin.
更多回答(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!