How to work with function inputs which are structures with different fields

1 回表示 (過去 30 日間)
KAE
KAE 2019 年 5 月 16 日
コメント済み: KAE 2019 年 5 月 16 日
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

採用された回答

Guillaume
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.
  1 件のコメント
KAE
KAE 2019 年 5 月 16 日
Thanks so much. I will work directly with varagin though I have to admit it makes the code a little hard to read.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by