Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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

Respuesta aceptada

Guillaume
Guillaume el 16 de Mayo de 2019
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 comentario
KAE
KAE el 16 de Mayo de 2019
Thanks so much. I will work directly with varagin though I have to admit it makes the code a little hard to read.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by