How to work with function inputs which are structures with different fields
조회 수: 2 (최근 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!