File Exchange

image thumbnail

Pack & Unpack variables to & from structures with enhanced functionality

version 1.14 (15.4 KB) by Adi Navve
v2struct packs and unpacks variables to and from structures with enhanced functionality.


Updated 20 Nov 2014

View Version History

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

v2struct has dual functionality in packing & unpacking variables into structures and vice versa, according to the syntax and inputs.
Function features:
* Pack variables to structure with enhanced field naming
* Pack and update variables in existing structure
* Unpack variables from structure with enhanced variable naming
* Unpack only specific fields in a structure to variables
* Unpack without over writing existing variables in workspace

In addition to the obvious usage, this function could by highly useful for example in working with a function with multiple inputs. Packing variables before the call to the function, and unpacking it in the beginning of the function will make the function call shorter, more readable, and you would not have to worry about arguments order any more. Moreover you could leave the function as it is and you could pass same inputs to multiple functions, each of which will use its designated arguments placed in the structure.

Moreover, the function enables extracting specific fields from a structure according to field names. This enhances the flexibility and ease of use of structures, for example it allows you to pass same inputs as structures to multiple functions, each of which will use its designated
arguments placed in the structure.

Some examples:
Simple pack:
x = zeros(3);
y = 'Testing123';
z = cell(2,3);
fieldNames1 = {'fieldnames','x','y','z'};
fieldNames2 = {'fieldnames','a','b','c'};

>> S = v2struct(x,y,z)
S =
x: [3x3 double]
y: 'Testing123'
z: {2x3 cell}

pack with different field names:
>> S = v2struct(x,y,z, fieldNames2)
S =
a: [3x3 double]
b: 'Testing123'
c: {2x3 cell}

update existing structure with additional field:
>> S.oldField = 'field to be saved for future use'
>> S = v2struct(x2, nameOfStruct2Update, fieldNames3)
S =
oldField: 'field to be saved for future use'
x: [3x3 double]

simple unpack:
S.x = zeros(3);
S.y = 'Testing123';
S.z = cell(2,3);
fieldNames3 = {'y'};
>> v2struct(S)
y =

More examples, further comments and demo usage are available inside the .m file and the demo functions.

Comments, suggestions, bug reports and any other feedback is welcomed at adi.navve[at]gmail[dot]com

Inspired by the function 'mmv2truct' from the Mastering Matlab Toolbox (available free) by D.C. Hanselman, University of Maine, Orono, ME 04469 4/28/99, 9/29/99, renamed 10/19/99 Mastering MATLAB 5, Prentice Hall, ISBN 0-13-858366-8
available at:

Cite As

Adi Navve (2021). Pack & Unpack variables to & from structures with enhanced functionality (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (30)

Adam Gardiner-Hill

Marc Hutzli


Does unpacking go into the local or the global namespace?


Axel Sauer


Very useful!

Matt H


Yifei Wang

Shannon Locke

Richard Sims

Musa Furkan Keskin

This is a very useful tool for handling function inputs and outputs.

I have encountered a problem while using v2struct in a function where parfor loop is executed after unpacking the variables in struct using v2struct(params). Before the parfor loop, I have v2struct(params) line to unpack a variable (say, dummy_variable), but in the parfor loop MATLAB generates an error which says that dummy_variable is not defined, although it is unpacked and already in the workspace (confirmed by debugging). I have solved this problem by writing "dummy_variable = dummy_variable" before parfor loop, but this decreases the functionality of v2struct. So, how can we solve this issue with parfor loops?

Adam Danz


I encountered the exact same name collision problem that Christian Dorion mentioned in his comment below. If I unpack a structure in a function, and one of the resulting variable names is also a function name (it was "ngrid" in my case), then Matlab interprets the variable name as a function call. The strangest think is that if I do a "who" or "which" within the function, then Matlab correctly reports that ngrid is a variable. But then it fails to interpret it correctly. I have a very hard time coming up with an explanation for this behavior. Anyone?


Works like a charm! Kudos for the very good documentation.




Perfect! Exactly what I needed:) Cheers

Shawn Heide

Adi Navve

Hi Christian,
It seems you have stumbled upon a name collision issue combined with the issue that Matlab treats calling a command differently whether it is from the command line or within a function. I assume you have a function called 'sigma' in your Matlab's path. I did not find such function in my system so it could be a function you've created or a built-in function if you have toolboxes that I don't have or a different Matlab version. Try using 'which sigma' to find out details on sigma or better yet 'edit sigma' to edit the function. When I write a code I try to follow the practice of naming variables with a case specific name so to avoid collisions with function names or even other variables in my code.
I could also suggest a practice I've recently began using which helps me in debugging and sorting out issues such as this. I added the line 'dbstop if error' in the startup.m file so whenever an error is encountered during a run the debugger breaks in the line of the error. In your case the debugger would have stopped in a new window of the 'sigma' function.
I hope this helps. Cheers.

Christian Dorion

This is a nice tool; I had one of my own but never nearly as extensive as this one. Unfortunately, there seems to be an issue with variable names that are also function names. I couldn't solve it, maybe you could...

If, for example, you write

S = struct('sigma',0.25);

on the command prompt, you have that sigma is 0.25. However, if you wrap this into function test.m (not a script, a function) then you have this oddity:

>> test
Name Size Bytes Class Attributes

S 1x1 184 struct
sigma 1x1 8 double

??? Error using ==> sigma at 83
Not enough input arguments.

Error in ==> test at 5

where Matlab tries to call a function called sigma!?

Any clue?


Hi Adi
Thanks for your quick reply and support.
I would like a simple "+" funtion which combines the values from two similar structs into one. Field names and construction are equal on the inut structs. The structs are typically struct arrays with more than one level of struct arrays.
Looking forward to your next release.

Adi Navve

Hi Per,
Thank you. Regarding your questions, first, I can think of several ways to extract variables from a struct array. They differ in complexity, both in the implementation in the code and the functionality. Could you elaborate how you would like to use this?
Second, I written a simple function to do this and I will upload it shortly. I would send a link to it here once it is published.



Excellent m file, which simplifies my code a lot.
I wonder if it possible in a simple way to extract variables from a struct array?
Also is there a simple way to concatenate struct arrays with similar field names etc?

Adi Navve

Thank you Vesa for your suggestion. I've just uploaded an updated version with your suggestion included. It will be available in a few days.

Vesa Lehtinen

This is a good tool, thanks! To make it perfect, please include a new form:


This would return all variables of the current workspace as fields of S. This is sometimes very useful, especially when one wants to have access to internal variables of a function. Instead of script M-files, I use functions that return their internal variables in a v2struct-like way. This gives me full control over my workspace.

Adi Navve

Thomas, I am sorry but I have only little experience with Simulink. However It seems like the function fits exactly to your demands. Maybe you could try and use it within a S-function? Have you tried posting a question in Matlab Central Answers? In anyway I would like to hear how it helped you further. Good luck!

Thomas Marullo

Is it possible to use this for Matlab Embedded Functions? I am trying to solve a problem where I have a model for xPC/Simulink and passing Structures is not supported. I've tried techniques where I convert Structures from the workspace into Arrays then in the model I convert it back to a struct into a Matlab Function using Bus building blocks. The problem is that I need to know the format of the struct ahead of time and my struct can change. This looks like a great approach and I wonder how I can apply this to Simulink Matlab Embedded Function some how.

Thanks for all your hard work.

Adi Navve

Nikolay, thank you for the feedback. I have addressed your issue in the last update. So now you can update an existing structure, by passing a variable with the name of the structure in the call to the function. An example is given in the file. I hope this answers your problem.

Nikolay S.

Excellent! Just what I was waiting for! This will allow me to use single input to my multiple inputs functions, with only minor modification. Works like magic!!!
A liitle improvenet would be nice: Note this function clears existing structure fields, while appending might sometimes be desirable.
See the case:
uFileds= {'uR','uG','uB'};
stdFileds= {'stdR','stdG','stdB'};
% will cleared uFileds, so I had to use

But anyhow, excellent code, great functionality, and very detailed documentation. Right on!

MATLAB Release Compatibility
Created with R2011a
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!