View License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Pack & Unpack variables to & from structures with enhanced functionality

5.0 | 14 ratings Rate this file 71 Downloads (last 30 days) File Size: 15.4 KB File ID: #31532 Version: 1.14
image thumbnail

Pack & Unpack variables to & from structures with enhanced functionality


Adi Navve (view profile)


23 May 2011 (Updated )

v2struct packs and unpacks variables to and from structures with enhanced functionality.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information

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:


This file inspired Implot Image Plot, Apply Multiple Functions In A Single Function., Crop Video To Sub Elements, Vars2struct, and Struct2vars.

Required Products MATLAB
MATLAB release MATLAB 7.12 (R2011a)
MATLAB Search Path
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (23)
13 Feb 2017 Yifei Wang

11 Feb 2017 Shannon Locke

06 Jun 2016 Richard Sims

08 Feb 2016 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?

27 Sep 2015 Adam Danz

Adam Danz (view profile)

01 Aug 2014 Andras

Andras (view profile)

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?

Comment only
01 Aug 2014 Andras

Andras (view profile)

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

23 Dec 2012 Jeff

Jeff (view profile)

18 May 2012 Jeff

Jeff (view profile)

10 May 2012 Paul

Paul (view profile)

Perfect! Exactly what I needed:) Cheers

30 Apr 2012 Shawn Heide

07 Dec 2011 Adi Navve

Adi Navve (view profile)

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.

Comment only
06 Dec 2011 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?

Comment only
07 Nov 2011 Per

Per (view profile)

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.

Comment only
06 Nov 2011 Adi Navve

Adi Navve (view profile)

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.

Comment only
05 Nov 2011 Shatrughan

04 Nov 2011 Per

Per (view profile)

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?

12 Sep 2011 Adi Navve

Adi Navve (view profile)

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.

Comment only
11 Sep 2011 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.

Comment only
07 Aug 2011 Adi Navve

Adi Navve (view profile)

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!

Comment only
05 Aug 2011 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.

29 May 2011 Adi Navve

Adi Navve (view profile)

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.

Comment only
25 May 2011 Nikolay S.

Nikolay S. (view profile)

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!

29 May 2011 1.4

added update structure functionality, made some documentation and demo function changes, added image :)

05 Jun 2011 1.5

* Added functionality: avoid overwritring existing variables
* Added 'unpacking' examples to demo1 .m file.

30 Jun 2011 1.7

fieldNames usage corrected, now for triggering a specific string must be included. Documentation enhanced. Code tweaked.

14 Jul 2011 1.8

fixed bug in packing with variables only

14 Aug 2011 1.11

Clarified warning and error when packing/unpacking with fieldNames.

12 Sep 2011 1.13

Added easy packing of all variables in caller workspace (thanks to Vesa Lehtinen for the suggestion), fixed bug in warning handling in packing case, edited comments.

20 Nov 2014 1.14

Made submission availavble as a toolbox

Contact us