Version 1.0.1 (2.83 KB) by Hank
fields2struct provides a clean but powerful way to initialize a structure
Updated 10 Apr 2020

View License

Initializing a struct is helpful, both for allocation and to ensure the
order of fields in a structure is well defined (programmer preference).
When a structure has a lot of fields and they're all empty, its clunky to
write s = struct('a',[],'b',[],'c',[], ... ). fields2struct provides a
quick way of initializing a struct with fields such as a,b,c... with a
empty or user defined initial values

s = fields2struct('field1','field2',...,'fieldN') creates a struct with N fields
- By default, the initial values are empty [] double arrays. Fieldnames
must be valid MATLAB variable names. Any invalid fieldnames will be
made valid with genvarname.
s = fields2struct(C) Fieldnames and order are derived cell array C
s = fields2struct(val,___) val is used as the default value.
Instead of [], the default value of all fields will populate with val
- In order to set the default value as a char array, use val = {'str'},
(set it inside of a 1x1 cell) as the first argument
- To define all the fields of the struct, set val 1xN cell array
containing the field values. Of course, this is a redundant way to
initialize a struct, but features are always good.
- Otherwise, if val is an NxM cell, the resulting structure will be NxM
with s(i,j).(field) = val(i,j) for all fields and i=1:n, j=1:m. This
generalized to n-dimensions

Cite As

Hank (2024). fields2struct (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2020a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes

Fixed bugs detecting cell inputs to 'val'